2020-10-05 00:17:53 +08:00
|
|
|
use std::collections::{BTreeMap, HashMap};
|
2020-10-04 19:17:58 +08:00
|
|
|
use std::convert::TryFrom;
|
2020-08-28 21:38:05 +08:00
|
|
|
use std::fs::File;
|
2020-08-06 18:38:42 +08:00
|
|
|
use std::io::{self, Read, Write};
|
2020-08-04 21:19:21 +08:00
|
|
|
use std::iter::FromIterator;
|
2020-07-07 17:32:33 +08:00
|
|
|
use std::path::PathBuf;
|
2020-09-21 20:59:48 +08:00
|
|
|
use std::{iter, thread};
|
2020-07-02 04:45:43 +08:00
|
|
|
use std::time::Instant;
|
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
use anyhow::{Context, bail};
|
2020-08-16 02:37:13 +08:00
|
|
|
use bstr::ByteSlice as _;
|
2020-08-31 20:20:42 +08:00
|
|
|
use csv::StringRecord;
|
2020-08-22 00:10:24 +08:00
|
|
|
use flate2::read::GzDecoder;
|
2020-08-06 17:08:24 +08:00
|
|
|
use fst::IntoStreamer;
|
2020-10-04 19:17:58 +08:00
|
|
|
use heed::{EnvOpenOptions, BytesEncode, types::ByteSlice};
|
2020-09-23 20:50:52 +08:00
|
|
|
use linked_hash_map::LinkedHashMap;
|
2020-08-28 21:38:05 +08:00
|
|
|
use log::{debug, info};
|
2020-08-04 21:19:21 +08:00
|
|
|
use memmap::Mmap;
|
|
|
|
use oxidized_mtbl::{Reader, Writer, Merger, Sorter, CompressionType};
|
2020-07-07 18:21:22 +08:00
|
|
|
use rayon::prelude::*;
|
2020-06-30 01:48:02 +08:00
|
|
|
use roaring::RoaringBitmap;
|
2020-05-26 02:39:53 +08:00
|
|
|
use structopt::StructOpt;
|
2020-10-04 19:17:58 +08:00
|
|
|
use tempfile::tempfile;
|
2020-05-26 02:39:53 +08:00
|
|
|
|
2020-10-01 17:14:26 +08:00
|
|
|
use milli::heed_codec::{CsvStringRecordCodec, BoRoaringBitmapCodec, CboRoaringBitmapCodec};
|
2020-09-22 16:24:31 +08:00
|
|
|
use milli::tokenizer::{simple_tokenizer, only_token};
|
2020-10-04 19:17:58 +08:00
|
|
|
use milli::{SmallVec32, Index, Position, DocumentId};
|
2020-07-07 17:32:33 +08:00
|
|
|
|
2020-08-16 02:37:13 +08:00
|
|
|
const LMDB_MAX_KEY_LENGTH: usize = 511;
|
2020-06-05 22:32:14 +08:00
|
|
|
|
|
|
|
const MAX_POSITION: usize = 1000;
|
|
|
|
const MAX_ATTRIBUTES: usize = u32::max_value() as usize / MAX_POSITION;
|
2020-05-26 02:39:53 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
const WORDS_FST_KEY: &[u8] = milli::WORDS_FST_KEY.as_bytes();
|
|
|
|
const HEADERS_KEY: &[u8] = milli::HEADERS_KEY.as_bytes();
|
|
|
|
const DOCUMENTS_IDS_KEY: &[u8] = milli::DOCUMENTS_IDS_KEY.as_bytes();
|
2020-08-04 21:19:21 +08:00
|
|
|
|
2020-05-26 02:39:53 +08:00
|
|
|
#[cfg(target_os = "linux")]
|
|
|
|
#[global_allocator]
|
|
|
|
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
|
|
|
|
|
|
|
|
#[derive(Debug, StructOpt)]
|
2020-08-21 22:41:26 +08:00
|
|
|
#[structopt(name = "milli-indexer")]
|
|
|
|
/// The indexer binary of the milli project.
|
2020-05-26 02:39:53 +08:00
|
|
|
struct Opt {
|
|
|
|
/// The database path where the database is located.
|
|
|
|
/// It is created if it doesn't already exist.
|
|
|
|
#[structopt(long = "db", parse(from_os_str))]
|
|
|
|
database: PathBuf,
|
|
|
|
|
2020-08-10 19:53:53 +08:00
|
|
|
/// The maximum size the database can take on disk. It is recommended to specify
|
|
|
|
/// the whole disk space (value must be a multiple of a page size).
|
|
|
|
#[structopt(long = "db-size", default_value = "107374182400")] // 100 GB
|
|
|
|
database_size: usize,
|
|
|
|
|
2020-06-28 18:13:10 +08:00
|
|
|
/// Number of parallel jobs, defaults to # of CPUs.
|
|
|
|
#[structopt(short, long)]
|
|
|
|
jobs: Option<usize>,
|
|
|
|
|
2020-08-21 22:41:26 +08:00
|
|
|
#[structopt(flatten)]
|
|
|
|
indexer: IndexerOpt,
|
|
|
|
|
|
|
|
/// Verbose mode (-v, -vv, -vvv, etc.)
|
|
|
|
#[structopt(short, long, parse(from_occurrences))]
|
|
|
|
verbose: usize,
|
|
|
|
|
|
|
|
/// CSV file to index, if unspecified the CSV is read from standard input.
|
2020-08-21 22:08:32 +08:00
|
|
|
///
|
2020-08-22 00:10:24 +08:00
|
|
|
/// You can also provide a ".gz" or ".gzip" CSV file, the indexer will figure out
|
|
|
|
/// how to decode and read it.
|
|
|
|
///
|
2020-08-21 22:08:32 +08:00
|
|
|
/// Note that it is much faster to index from a file as when the indexer reads from stdin
|
|
|
|
/// it will dedicate a thread for that and context switches could slow down the indexing jobs.
|
2020-08-21 22:41:26 +08:00
|
|
|
csv_file: Option<PathBuf>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, StructOpt)]
|
|
|
|
struct IndexerOpt {
|
2020-09-29 21:10:08 +08:00
|
|
|
/// The amount of documents to skip before printing
|
|
|
|
/// a log regarding the indexing advancement.
|
|
|
|
#[structopt(long, default_value = "1000000")] // 1m
|
|
|
|
log_every_n: usize,
|
|
|
|
|
2020-08-05 18:10:41 +08:00
|
|
|
/// MTBL max number of chunks in bytes.
|
|
|
|
#[structopt(long)]
|
|
|
|
max_nb_chunks: Option<usize>,
|
|
|
|
|
|
|
|
/// MTBL max memory in bytes.
|
2020-10-05 00:17:53 +08:00
|
|
|
#[structopt(long, default_value = "440401920")] // 420 MB
|
2020-09-23 17:54:41 +08:00
|
|
|
max_memory: usize,
|
2020-08-05 18:10:41 +08:00
|
|
|
|
2020-09-23 20:50:52 +08:00
|
|
|
/// Size of the linked hash map cache when indexing.
|
|
|
|
/// The bigger it is, the faster the indexing is but the more memory it takes.
|
2020-09-29 21:09:18 +08:00
|
|
|
#[structopt(long, default_value = "524288")]
|
2020-09-23 20:50:52 +08:00
|
|
|
linked_hash_map_size: usize,
|
2020-08-06 17:08:24 +08:00
|
|
|
|
2020-08-21 22:41:26 +08:00
|
|
|
/// The name of the compression algorithm to use when compressing intermediate
|
|
|
|
/// chunks during indexing documents.
|
|
|
|
///
|
|
|
|
/// Choosing a fast algorithm will make the indexing faster but may consume more memory.
|
|
|
|
#[structopt(long, default_value = "snappy", possible_values = &["snappy", "zlib", "lz4", "lz4hc", "zstd"])]
|
|
|
|
chunk_compression_type: String,
|
2020-07-12 17:04:35 +08:00
|
|
|
|
2020-08-21 22:41:26 +08:00
|
|
|
/// The level of compression of the chosen algorithm.
|
|
|
|
#[structopt(long, requires = "chunk-compression-type")]
|
|
|
|
chunk_compression_level: Option<u32>,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn compression_type_from_str(name: &str) -> CompressionType {
|
|
|
|
match name {
|
|
|
|
"snappy" => CompressionType::Snappy,
|
|
|
|
"zlib" => CompressionType::Zlib,
|
|
|
|
"lz4" => CompressionType::Lz4,
|
|
|
|
"lz4hc" => CompressionType::Lz4hc,
|
|
|
|
"zstd" => CompressionType::Zstd,
|
|
|
|
_ => panic!("invalid compression algorithm"),
|
|
|
|
}
|
2020-05-30 21:35:33 +08:00
|
|
|
}
|
|
|
|
|
2020-09-29 21:10:08 +08:00
|
|
|
fn format_count(n: usize) -> String {
|
|
|
|
human_format::Formatter::new().with_decimals(1).with_separator("").format(n as f64)
|
|
|
|
}
|
|
|
|
|
2020-08-05 18:10:41 +08:00
|
|
|
fn lmdb_key_valid_size(key: &[u8]) -> bool {
|
|
|
|
!key.is_empty() && key.len() <= LMDB_MAX_KEY_LENGTH
|
|
|
|
}
|
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
fn create_writer(typ: CompressionType, level: Option<u32>, file: File) -> Writer<File> {
|
2020-09-22 00:30:42 +08:00
|
|
|
let mut builder = Writer::builder();
|
2020-10-04 19:17:58 +08:00
|
|
|
builder.compression_type(typ);
|
2020-09-22 00:30:42 +08:00
|
|
|
if let Some(level) = level {
|
|
|
|
builder.compression_level(level);
|
|
|
|
}
|
|
|
|
builder.build(file)
|
|
|
|
}
|
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
fn writer_into_reader(writer: Writer<File>) -> anyhow::Result<Reader<Mmap>> {
|
|
|
|
let file = writer.into_inner()?;
|
|
|
|
let mmap = unsafe { Mmap::map(&file)? };
|
|
|
|
Reader::new(mmap).map_err(Into::into)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn create_sorter(
|
|
|
|
merge: MergeFn,
|
|
|
|
chunk_compression_type: CompressionType,
|
|
|
|
chunk_compression_level: Option<u32>,
|
|
|
|
max_nb_chunks: Option<usize>,
|
|
|
|
max_memory: Option<usize>,
|
|
|
|
) -> Sorter<MergeFn>
|
|
|
|
{
|
|
|
|
let mut builder = Sorter::builder(merge);
|
|
|
|
builder.chunk_compression_type(chunk_compression_type);
|
|
|
|
if let Some(level) = chunk_compression_level {
|
|
|
|
builder.chunk_compression_level(level);
|
|
|
|
}
|
|
|
|
if let Some(nb_chunks) = max_nb_chunks {
|
|
|
|
builder.max_nb_chunks(nb_chunks);
|
|
|
|
}
|
|
|
|
if let Some(memory) = max_memory {
|
|
|
|
builder.max_memory(memory);
|
|
|
|
}
|
|
|
|
builder.build()
|
|
|
|
}
|
|
|
|
|
2020-09-29 21:09:18 +08:00
|
|
|
/// Outputs a list of all pairs of words with the shortest proximity between 1 and 7 inclusive.
|
2020-09-23 21:02:40 +08:00
|
|
|
///
|
2020-09-29 21:09:18 +08:00
|
|
|
/// This list is used by the engine to calculate the documents containing words that are
|
2020-09-23 21:02:40 +08:00
|
|
|
/// close to each other.
|
2020-09-22 20:04:33 +08:00
|
|
|
fn compute_words_pair_proximities(
|
2020-09-29 21:09:18 +08:00
|
|
|
word_positions: &HashMap<String, SmallVec32<Position>>,
|
|
|
|
) -> HashMap<(&str, &str), u8>
|
2020-09-22 20:04:33 +08:00
|
|
|
{
|
|
|
|
use itertools::Itertools;
|
|
|
|
|
|
|
|
let mut words_pair_proximities = HashMap::new();
|
2020-09-29 21:09:18 +08:00
|
|
|
for ((w1, ps1), (w2, ps2)) in word_positions.iter().cartesian_product(word_positions) {
|
|
|
|
let mut min_prox = None;
|
|
|
|
for (ps1, ps2) in ps1.iter().cartesian_product(ps2) {
|
2020-09-22 20:04:33 +08:00
|
|
|
let prox = milli::proximity::positions_proximity(*ps1, *ps2);
|
2020-09-29 21:09:18 +08:00
|
|
|
let prox = u8::try_from(prox).unwrap();
|
2020-09-22 20:04:33 +08:00
|
|
|
// We don't care about a word that appear at the
|
|
|
|
// same position or too far from the other.
|
2020-09-29 21:09:18 +08:00
|
|
|
if prox >= 1 && prox <= 7 {
|
|
|
|
match min_prox {
|
|
|
|
None => min_prox = Some(prox),
|
|
|
|
Some(mp) => if prox < mp { min_prox = Some(prox) },
|
|
|
|
}
|
|
|
|
}
|
2020-09-22 20:04:33 +08:00
|
|
|
}
|
2020-09-29 21:09:18 +08:00
|
|
|
|
|
|
|
if let Some(min_prox) = min_prox {
|
|
|
|
words_pair_proximities.insert((w1.as_str(), w2.as_str()), min_prox);
|
2020-09-22 20:04:33 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
words_pair_proximities
|
|
|
|
}
|
|
|
|
|
2020-08-04 21:19:21 +08:00
|
|
|
type MergeFn = fn(&[u8], &[Vec<u8>]) -> Result<Vec<u8>, ()>;
|
|
|
|
|
2020-10-05 00:17:53 +08:00
|
|
|
struct Readers {
|
|
|
|
main: Reader<Mmap>,
|
|
|
|
word_docids: Reader<Mmap>,
|
|
|
|
docid_word_positions: Reader<Mmap>,
|
|
|
|
words_pairs_proximities_docids: Reader<Mmap>,
|
|
|
|
documents: Reader<Mmap>,
|
|
|
|
}
|
|
|
|
|
2020-08-04 21:19:21 +08:00
|
|
|
struct Store {
|
2020-09-23 20:50:52 +08:00
|
|
|
word_docids: LinkedHashMap<SmallVec32<u8>, RoaringBitmap>,
|
2020-09-27 17:46:52 +08:00
|
|
|
word_docids_limit: usize,
|
2020-09-29 21:09:18 +08:00
|
|
|
words_pairs_proximities_docids: LinkedHashMap<(SmallVec32<u8>, SmallVec32<u8>, u8), RoaringBitmap>,
|
|
|
|
words_pairs_proximities_docids_limit: usize,
|
2020-08-29 21:14:04 +08:00
|
|
|
documents_ids: RoaringBitmap,
|
2020-10-04 19:17:58 +08:00
|
|
|
// MTBL parameters
|
2020-09-22 00:30:42 +08:00
|
|
|
chunk_compression_type: CompressionType,
|
|
|
|
chunk_compression_level: Option<u32>,
|
2020-10-04 19:17:58 +08:00
|
|
|
// MTBL sorters
|
|
|
|
main_sorter: Sorter<MergeFn>,
|
|
|
|
word_docids_sorter: Sorter<MergeFn>,
|
|
|
|
words_pairs_proximities_docids_sorter: Sorter<MergeFn>,
|
|
|
|
// MTBL writers
|
2020-10-05 00:17:53 +08:00
|
|
|
docid_word_positions_writer: Writer<File>,
|
2020-10-04 19:17:58 +08:00
|
|
|
documents_writer: Writer<File>,
|
|
|
|
}
|
|
|
|
|
2020-08-04 21:19:21 +08:00
|
|
|
impl Store {
|
2020-09-21 20:59:48 +08:00
|
|
|
pub fn new(
|
2020-09-23 20:50:52 +08:00
|
|
|
linked_hash_map_size: usize,
|
2020-08-21 22:41:26 +08:00
|
|
|
max_nb_chunks: Option<usize>,
|
|
|
|
max_memory: Option<usize>,
|
|
|
|
chunk_compression_type: CompressionType,
|
|
|
|
chunk_compression_level: Option<u32>,
|
2020-09-27 17:46:52 +08:00
|
|
|
) -> anyhow::Result<Store>
|
2020-08-21 22:41:26 +08:00
|
|
|
{
|
2020-10-04 19:17:58 +08:00
|
|
|
let main_sorter = create_sorter(
|
|
|
|
main_merge,
|
|
|
|
chunk_compression_type,
|
|
|
|
chunk_compression_level,
|
|
|
|
max_nb_chunks,
|
|
|
|
max_memory,
|
|
|
|
);
|
|
|
|
let word_docids_sorter = create_sorter(
|
|
|
|
word_docids_merge,
|
|
|
|
chunk_compression_type,
|
|
|
|
chunk_compression_level,
|
|
|
|
max_nb_chunks,
|
|
|
|
max_memory,
|
|
|
|
);
|
|
|
|
let words_pairs_proximities_docids_sorter = create_sorter(
|
|
|
|
words_pairs_proximities_docids_merge,
|
|
|
|
chunk_compression_type,
|
|
|
|
chunk_compression_level,
|
|
|
|
max_nb_chunks,
|
|
|
|
max_memory,
|
|
|
|
);
|
2020-08-04 21:19:21 +08:00
|
|
|
|
2020-10-05 00:17:53 +08:00
|
|
|
let documents_writer = tempfile().map(|f| {
|
|
|
|
create_writer(chunk_compression_type, chunk_compression_level, f)
|
|
|
|
})?;
|
|
|
|
let docid_word_positions_writer = tempfile().map(|f| {
|
|
|
|
create_writer(chunk_compression_type, chunk_compression_level, f)
|
|
|
|
})?;
|
2020-08-07 00:19:10 +08:00
|
|
|
|
2020-09-27 17:46:52 +08:00
|
|
|
Ok(Store {
|
|
|
|
word_docids: LinkedHashMap::with_capacity(linked_hash_map_size),
|
|
|
|
word_docids_limit: linked_hash_map_size,
|
2020-09-29 21:09:18 +08:00
|
|
|
words_pairs_proximities_docids: LinkedHashMap::with_capacity(linked_hash_map_size),
|
|
|
|
words_pairs_proximities_docids_limit: linked_hash_map_size,
|
2020-08-29 21:14:04 +08:00
|
|
|
documents_ids: RoaringBitmap::new(),
|
2020-09-22 00:30:42 +08:00
|
|
|
chunk_compression_type,
|
|
|
|
chunk_compression_level,
|
2020-10-04 19:17:58 +08:00
|
|
|
|
|
|
|
main_sorter,
|
|
|
|
word_docids_sorter,
|
|
|
|
words_pairs_proximities_docids_sorter,
|
|
|
|
|
2020-10-05 00:17:53 +08:00
|
|
|
docid_word_positions_writer,
|
2020-10-04 19:17:58 +08:00
|
|
|
documents_writer,
|
2020-09-27 17:46:52 +08:00
|
|
|
})
|
2020-08-04 21:19:21 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Save the documents ids under the position and word we have seen it.
|
2020-09-21 20:59:48 +08:00
|
|
|
fn insert_word_docid(&mut self, word: &str, id: DocumentId) -> anyhow::Result<()> {
|
2020-09-23 20:50:52 +08:00
|
|
|
// if get_refresh finds the element it is assured to be at the end of the linked hash map.
|
2020-09-27 17:46:52 +08:00
|
|
|
match self.word_docids.get_refresh(word.as_bytes()) {
|
2020-09-23 20:50:52 +08:00
|
|
|
Some(old) => { old.insert(id); },
|
|
|
|
None => {
|
2020-09-27 17:46:52 +08:00
|
|
|
let word_vec = SmallVec32::from(word.as_bytes());
|
2020-09-23 20:50:52 +08:00
|
|
|
// A newly inserted element is append at the end of the linked hash map.
|
|
|
|
self.word_docids.insert(word_vec, RoaringBitmap::from_iter(Some(id)));
|
|
|
|
// If the word docids just reached it's capacity we must make sure to remove
|
|
|
|
// one element, this way next time we insert we doesn't grow the capacity.
|
2020-09-27 17:46:52 +08:00
|
|
|
if self.word_docids.len() == self.word_docids_limit {
|
2020-09-23 20:50:52 +08:00
|
|
|
// Removing the front element is equivalent to removing the LRU element.
|
|
|
|
let lru = self.word_docids.pop_front();
|
2020-10-04 19:17:58 +08:00
|
|
|
Self::write_word_docids(&mut self.word_docids_sorter, lru)?;
|
2020-09-23 20:50:52 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-08-29 22:29:18 +08:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-09-29 21:09:18 +08:00
|
|
|
// Save the documents ids under the words pairs proximities that it contains.
|
|
|
|
fn insert_words_pairs_proximities_docids<'a>(
|
|
|
|
&mut self,
|
|
|
|
words_pairs_proximities: impl IntoIterator<Item=((&'a str, &'a str), u8)>,
|
|
|
|
id: DocumentId,
|
|
|
|
) -> anyhow::Result<()>
|
|
|
|
{
|
|
|
|
for ((w1, w2), prox) in words_pairs_proximities {
|
|
|
|
let w1 = SmallVec32::from(w1.as_bytes());
|
|
|
|
let w2 = SmallVec32::from(w2.as_bytes());
|
|
|
|
let key = (w1, w2, prox);
|
|
|
|
// if get_refresh finds the element it is assured
|
|
|
|
// to be at the end of the linked hash map.
|
|
|
|
match self.words_pairs_proximities_docids.get_refresh(&key) {
|
|
|
|
Some(old) => { old.insert(id); },
|
|
|
|
None => {
|
|
|
|
// A newly inserted element is append at the end of the linked hash map.
|
|
|
|
let ids = RoaringBitmap::from_iter(Some(id));
|
|
|
|
self.words_pairs_proximities_docids.insert(key, ids);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the linked hashmap is over capacity we must remove the overflowing elements.
|
|
|
|
let len = self.words_pairs_proximities_docids.len();
|
|
|
|
let overflow = len.checked_sub(self.words_pairs_proximities_docids_limit);
|
|
|
|
if let Some(overflow) = overflow {
|
|
|
|
let mut lrus = Vec::with_capacity(overflow);
|
|
|
|
// Removing front elements is equivalent to removing the LRUs.
|
|
|
|
let iter = iter::from_fn(|| self.words_pairs_proximities_docids.pop_front());
|
|
|
|
iter.take(overflow).for_each(|x| lrus.push(x));
|
2020-10-04 19:17:58 +08:00
|
|
|
Self::write_words_pairs_proximities(&mut self.words_pairs_proximities_docids_sorter, lrus)?;
|
2020-09-29 21:09:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-09-21 20:59:48 +08:00
|
|
|
fn write_headers(&mut self, headers: &StringRecord) -> anyhow::Result<()> {
|
2020-08-31 20:20:42 +08:00
|
|
|
let headers = CsvStringRecordCodec::bytes_encode(headers)
|
|
|
|
.with_context(|| format!("could not encode csv record"))?;
|
2020-10-04 19:17:58 +08:00
|
|
|
Ok(self.main_sorter.insert(HEADERS_KEY, headers)?)
|
2020-08-04 21:19:21 +08:00
|
|
|
}
|
2020-07-07 17:32:33 +08:00
|
|
|
|
2020-09-21 20:59:48 +08:00
|
|
|
fn write_document(
|
2020-09-06 00:03:06 +08:00
|
|
|
&mut self,
|
2020-09-22 16:33:25 +08:00
|
|
|
document_id: DocumentId,
|
2020-09-29 21:09:18 +08:00
|
|
|
words_positions: &HashMap<String, SmallVec32<Position>>,
|
2020-09-06 00:03:06 +08:00
|
|
|
record: &StringRecord,
|
|
|
|
) -> anyhow::Result<()>
|
|
|
|
{
|
2020-09-23 21:02:40 +08:00
|
|
|
// We compute the list of words pairs proximities (self-join) and write it directly to disk.
|
|
|
|
let words_pair_proximities = compute_words_pair_proximities(&words_positions);
|
2020-09-29 21:09:18 +08:00
|
|
|
self.insert_words_pairs_proximities_docids(words_pair_proximities, document_id)?;
|
2020-09-23 21:02:40 +08:00
|
|
|
|
2020-09-22 16:33:25 +08:00
|
|
|
// We store document_id associated with all the words the record contains.
|
|
|
|
for (word, _) in words_positions {
|
|
|
|
self.insert_word_docid(word, document_id)?;
|
|
|
|
}
|
|
|
|
|
2020-08-31 20:20:42 +08:00
|
|
|
let record = CsvStringRecordCodec::bytes_encode(record)
|
2020-09-22 16:33:25 +08:00
|
|
|
.with_context(|| format!("could not encode CSV record"))?;
|
|
|
|
|
|
|
|
self.documents_ids.insert(document_id);
|
2020-09-27 17:46:52 +08:00
|
|
|
self.documents_writer.insert(document_id.to_be_bytes(), record)?;
|
2020-10-05 00:17:53 +08:00
|
|
|
Self::write_docid_word_positions(&mut self.docid_word_positions_writer, document_id, words_positions)?;
|
2020-09-22 16:33:25 +08:00
|
|
|
|
2020-08-04 21:19:21 +08:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-09-23 21:02:40 +08:00
|
|
|
fn write_words_pairs_proximities(
|
2020-09-22 20:04:33 +08:00
|
|
|
sorter: &mut Sorter<MergeFn>,
|
2020-09-29 21:09:18 +08:00
|
|
|
iter: impl IntoIterator<Item=((SmallVec32<u8>, SmallVec32<u8>, u8), RoaringBitmap)>,
|
2020-09-22 20:04:33 +08:00
|
|
|
) -> anyhow::Result<()>
|
|
|
|
{
|
2020-10-04 19:17:58 +08:00
|
|
|
let mut key = Vec::new();
|
2020-09-22 20:04:33 +08:00
|
|
|
let mut buffer = Vec::new();
|
|
|
|
|
2020-09-29 21:09:18 +08:00
|
|
|
for ((w1, w2, min_prox), docids) in iter {
|
2020-10-04 19:17:58 +08:00
|
|
|
key.clear();
|
2020-09-22 20:04:33 +08:00
|
|
|
key.extend_from_slice(w1.as_bytes());
|
|
|
|
key.push(0);
|
|
|
|
key.extend_from_slice(w2.as_bytes());
|
2020-09-29 21:09:18 +08:00
|
|
|
// Storing the minimun proximity found between those words
|
|
|
|
key.push(min_prox);
|
|
|
|
// We serialize the document ids into a buffer
|
|
|
|
buffer.clear();
|
2020-10-01 17:14:26 +08:00
|
|
|
buffer.reserve(CboRoaringBitmapCodec::serialized_size(&docids));
|
|
|
|
CboRoaringBitmapCodec::serialize_into(&docids, &mut buffer)?;
|
2020-09-29 21:09:18 +08:00
|
|
|
// that we write under the generated key into MTBL
|
|
|
|
if lmdb_key_valid_size(&key) {
|
|
|
|
sorter.insert(&key, &buffer)?;
|
2020-09-22 20:04:33 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-09-22 16:33:25 +08:00
|
|
|
fn write_docid_word_positions(
|
2020-10-05 00:17:53 +08:00
|
|
|
writer: &mut Writer<File>,
|
2020-09-22 16:33:25 +08:00
|
|
|
id: DocumentId,
|
2020-09-29 21:09:18 +08:00
|
|
|
words_positions: &HashMap<String, SmallVec32<Position>>,
|
2020-09-22 16:33:25 +08:00
|
|
|
) -> anyhow::Result<()>
|
2020-08-04 21:19:21 +08:00
|
|
|
{
|
2020-09-06 16:30:53 +08:00
|
|
|
// We prefix the words by the document id.
|
2020-10-04 19:17:58 +08:00
|
|
|
let mut key = id.to_be_bytes().to_vec();
|
2020-09-06 23:33:26 +08:00
|
|
|
let base_size = key.len();
|
2020-09-06 16:30:53 +08:00
|
|
|
|
2020-10-05 00:17:53 +08:00
|
|
|
// We order the words lexicographically, this way we avoid passing by a sorter.
|
|
|
|
let words_positions = BTreeMap::from_iter(words_positions);
|
|
|
|
|
2020-09-22 16:33:25 +08:00
|
|
|
for (word, positions) in words_positions {
|
2020-09-06 23:33:26 +08:00
|
|
|
key.truncate(base_size);
|
2020-09-06 00:03:06 +08:00
|
|
|
key.extend_from_slice(word.as_bytes());
|
2020-09-06 23:33:26 +08:00
|
|
|
// We serialize the positions into a buffer.
|
2020-09-29 21:09:18 +08:00
|
|
|
let positions = RoaringBitmap::from_iter(positions.iter().cloned());
|
2020-10-01 16:58:19 +08:00
|
|
|
let bytes = BoRoaringBitmapCodec::bytes_encode(&positions)
|
2020-10-01 17:14:26 +08:00
|
|
|
.with_context(|| "could not serialize positions")?;
|
2020-08-04 21:19:21 +08:00
|
|
|
// that we write under the generated key into MTBL
|
2020-08-05 18:10:41 +08:00
|
|
|
if lmdb_key_valid_size(&key) {
|
2020-10-05 00:17:53 +08:00
|
|
|
writer.insert(&key, &bytes)?;
|
2020-08-05 18:10:41 +08:00
|
|
|
}
|
2020-07-01 23:24:55 +08:00
|
|
|
}
|
2020-07-07 17:32:33 +08:00
|
|
|
|
2020-08-04 21:19:21 +08:00
|
|
|
Ok(())
|
2020-07-01 23:24:55 +08:00
|
|
|
}
|
|
|
|
|
2020-09-06 00:03:06 +08:00
|
|
|
fn write_word_docids<I>(sorter: &mut Sorter<MergeFn>, iter: I) -> anyhow::Result<()>
|
|
|
|
where I: IntoIterator<Item=(SmallVec32<u8>, RoaringBitmap)>
|
2020-08-29 22:29:18 +08:00
|
|
|
{
|
2020-10-04 19:17:58 +08:00
|
|
|
let mut key = Vec::new();
|
2020-08-29 22:29:18 +08:00
|
|
|
let mut buffer = Vec::new();
|
|
|
|
|
2020-09-06 00:03:06 +08:00
|
|
|
for (word, ids) in iter {
|
2020-10-04 19:17:58 +08:00
|
|
|
key.clear();
|
2020-08-29 22:29:18 +08:00
|
|
|
key.extend_from_slice(&word);
|
2020-08-06 17:08:24 +08:00
|
|
|
// We serialize the document ids into a buffer
|
|
|
|
buffer.clear();
|
2020-09-29 21:09:18 +08:00
|
|
|
let ids = RoaringBitmap::from_iter(ids);
|
2020-08-29 21:14:04 +08:00
|
|
|
buffer.reserve(ids.serialized_size());
|
2020-08-06 17:08:24 +08:00
|
|
|
ids.serialize_into(&mut buffer)?;
|
|
|
|
// that we write under the generated key into MTBL
|
|
|
|
if lmdb_key_valid_size(&key) {
|
|
|
|
sorter.insert(&key, &buffer)?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-08-29 21:14:04 +08:00
|
|
|
fn write_documents_ids(sorter: &mut Sorter<MergeFn>, ids: RoaringBitmap) -> anyhow::Result<()> {
|
|
|
|
let mut buffer = Vec::with_capacity(ids.serialized_size());
|
|
|
|
ids.serialize_into(&mut buffer)?;
|
|
|
|
sorter.insert(DOCUMENTS_IDS_KEY, &buffer)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-09-21 20:59:48 +08:00
|
|
|
pub fn index_csv(
|
|
|
|
mut self,
|
|
|
|
mut rdr: csv::Reader<Box<dyn Read + Send>>,
|
|
|
|
thread_index: usize,
|
|
|
|
num_threads: usize,
|
2020-09-29 21:10:08 +08:00
|
|
|
log_every_n: usize,
|
2020-10-04 19:17:58 +08:00
|
|
|
) -> anyhow::Result<Readers>
|
2020-09-21 20:59:48 +08:00
|
|
|
{
|
|
|
|
debug!("{:?}: Indexing in a Store...", thread_index);
|
|
|
|
|
|
|
|
// Write the headers into the store.
|
|
|
|
let headers = rdr.headers()?;
|
|
|
|
self.write_headers(&headers)?;
|
|
|
|
|
|
|
|
let mut before = Instant::now();
|
|
|
|
let mut document_id: usize = 0;
|
|
|
|
let mut document = csv::StringRecord::new();
|
2020-09-23 21:02:40 +08:00
|
|
|
let mut words_positions = HashMap::new();
|
2020-09-21 20:59:48 +08:00
|
|
|
|
2020-09-22 16:33:25 +08:00
|
|
|
while rdr.read_record(&mut document)? {
|
2020-09-21 20:59:48 +08:00
|
|
|
// We skip documents that must not be indexed by this thread.
|
|
|
|
if document_id % num_threads == thread_index {
|
2020-09-29 21:10:08 +08:00
|
|
|
// This is a log routine that we do every `log_every_n` documents.
|
|
|
|
if document_id % log_every_n == 0 {
|
|
|
|
let count = format_count(document_id);
|
|
|
|
info!("We have seen {} documents so far ({:.02?}).", count, before.elapsed());
|
2020-09-21 20:59:48 +08:00
|
|
|
before = Instant::now();
|
|
|
|
}
|
|
|
|
|
|
|
|
let document_id = DocumentId::try_from(document_id).context("generated id is too big")?;
|
|
|
|
for (attr, content) in document.iter().enumerate().take(MAX_ATTRIBUTES) {
|
2020-09-22 16:24:31 +08:00
|
|
|
for (pos, token) in simple_tokenizer(&content).filter_map(only_token).enumerate().take(MAX_POSITION) {
|
2020-09-21 20:59:48 +08:00
|
|
|
let word = token.to_lowercase();
|
|
|
|
let position = (attr * MAX_POSITION + pos) as u32;
|
2020-09-29 21:09:18 +08:00
|
|
|
words_positions.entry(word).or_insert_with(SmallVec32::new).push(position);
|
2020-09-21 20:59:48 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// We write the document in the documents store.
|
2020-09-23 21:02:40 +08:00
|
|
|
self.write_document(document_id, &words_positions, &document)?;
|
|
|
|
words_positions.clear();
|
2020-09-21 20:59:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Compute the document id of the next document.
|
|
|
|
document_id = document_id + 1;
|
|
|
|
}
|
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
let readers = self.finish()?;
|
2020-09-21 20:59:48 +08:00
|
|
|
debug!("{:?}: Store created!", thread_index);
|
2020-10-04 19:17:58 +08:00
|
|
|
Ok(readers)
|
2020-09-21 20:59:48 +08:00
|
|
|
}
|
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
fn finish(mut self) -> anyhow::Result<Readers> {
|
|
|
|
let comp_type = self.chunk_compression_type;
|
|
|
|
let comp_level = self.chunk_compression_level;
|
2020-09-22 00:30:42 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
Self::write_word_docids(&mut self.word_docids_sorter, self.word_docids)?;
|
|
|
|
Self::write_documents_ids(&mut self.main_sorter, self.documents_ids)?;
|
|
|
|
Self::write_words_pairs_proximities(
|
|
|
|
&mut self.words_pairs_proximities_docids_sorter,
|
|
|
|
self.words_pairs_proximities_docids,
|
|
|
|
)?;
|
2020-07-07 17:32:33 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
let mut word_docids_wtr = tempfile().map(|f| create_writer(comp_type, comp_level, f))?;
|
2020-08-04 21:19:21 +08:00
|
|
|
let mut builder = fst::SetBuilder::memory();
|
2020-07-07 17:32:33 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
let mut iter = self.word_docids_sorter.into_iter()?;
|
2020-08-04 21:19:21 +08:00
|
|
|
while let Some(result) = iter.next() {
|
2020-10-04 19:17:58 +08:00
|
|
|
let (word, val) = result?;
|
|
|
|
// This is a lexicographically ordered word position
|
|
|
|
// we use the key to construct the words fst.
|
|
|
|
builder.insert(word)?;
|
|
|
|
word_docids_wtr.insert(word, val)?;
|
2020-07-07 17:32:33 +08:00
|
|
|
}
|
|
|
|
|
2020-08-04 21:19:21 +08:00
|
|
|
let fst = builder.into_set();
|
2020-10-04 19:17:58 +08:00
|
|
|
self.main_sorter.insert(WORDS_FST_KEY, fst.as_fst().as_bytes())?;
|
|
|
|
|
|
|
|
let mut main_wtr = tempfile().map(|f| create_writer(comp_type, comp_level, f))?;
|
|
|
|
self.main_sorter.write_into(&mut main_wtr)?;
|
2020-07-07 17:32:33 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
let mut words_pairs_proximities_docids_wtr = tempfile().map(|f| create_writer(comp_type, comp_level, f))?;
|
|
|
|
self.words_pairs_proximities_docids_sorter.write_into(&mut words_pairs_proximities_docids_wtr)?;
|
2020-07-01 23:24:55 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
let main = writer_into_reader(main_wtr)?;
|
|
|
|
let word_docids = writer_into_reader(word_docids_wtr)?;
|
|
|
|
let words_pairs_proximities_docids = writer_into_reader(words_pairs_proximities_docids_wtr)?;
|
2020-10-05 00:17:53 +08:00
|
|
|
let docid_word_positions = writer_into_reader(self.docid_word_positions_writer)?;
|
2020-10-04 19:17:58 +08:00
|
|
|
let documents = writer_into_reader(self.documents_writer)?;
|
|
|
|
|
|
|
|
Ok(Readers {
|
|
|
|
main,
|
|
|
|
word_docids,
|
|
|
|
docid_word_positions,
|
|
|
|
words_pairs_proximities_docids,
|
|
|
|
documents,
|
|
|
|
})
|
2020-08-04 21:19:21 +08:00
|
|
|
}
|
|
|
|
}
|
2020-07-07 17:32:33 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
fn main_merge(key: &[u8], values: &[Vec<u8>]) -> Result<Vec<u8>, ()> {
|
2020-08-06 17:08:24 +08:00
|
|
|
match key {
|
|
|
|
WORDS_FST_KEY => {
|
|
|
|
let fsts: Vec<_> = values.iter().map(|v| fst::Set::new(v).unwrap()).collect();
|
|
|
|
|
2020-08-31 03:50:30 +08:00
|
|
|
// Union of the FSTs
|
2020-08-06 17:08:24 +08:00
|
|
|
let mut op = fst::set::OpBuilder::new();
|
|
|
|
fsts.iter().for_each(|fst| op.push(fst.into_stream()));
|
|
|
|
let op = op.r#union();
|
|
|
|
|
|
|
|
let mut build = fst::SetBuilder::memory();
|
|
|
|
build.extend_stream(op.into_stream()).unwrap();
|
|
|
|
Ok(build.into_inner().unwrap())
|
|
|
|
},
|
2020-10-04 19:17:58 +08:00
|
|
|
HEADERS_KEY => {
|
|
|
|
assert!(values.windows(2).all(|vs| vs[0] == vs[1]));
|
|
|
|
Ok(values[0].to_vec())
|
|
|
|
},
|
|
|
|
DOCUMENTS_IDS_KEY => word_docids_merge(&[], values),
|
|
|
|
otherwise => panic!("wut {:?}", otherwise),
|
|
|
|
}
|
|
|
|
}
|
2020-07-07 17:32:33 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
fn word_docids_merge(_key: &[u8], values: &[Vec<u8>]) -> Result<Vec<u8>, ()> {
|
|
|
|
let (head, tail) = values.split_first().unwrap();
|
|
|
|
let mut head = RoaringBitmap::deserialize_from(head.as_slice()).unwrap();
|
2020-10-01 17:14:26 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
for value in tail {
|
|
|
|
let bitmap = RoaringBitmap::deserialize_from(value.as_slice()).unwrap();
|
|
|
|
head.union_with(&bitmap);
|
2020-07-07 17:32:33 +08:00
|
|
|
}
|
2020-10-04 19:17:58 +08:00
|
|
|
|
|
|
|
let mut vec = Vec::with_capacity(head.serialized_size());
|
|
|
|
head.serialize_into(&mut vec).unwrap();
|
|
|
|
Ok(vec)
|
2020-07-01 23:24:55 +08:00
|
|
|
}
|
|
|
|
|
2020-10-04 23:31:12 +08:00
|
|
|
fn docid_word_positions_merge(key: &[u8], _values: &[Vec<u8>]) -> Result<Vec<u8>, ()> {
|
2020-10-05 00:17:53 +08:00
|
|
|
panic!("merging docid word positions is an error ({:?})", key.as_bstr())
|
2020-10-04 19:17:58 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
fn words_pairs_proximities_docids_merge(_key: &[u8], values: &[Vec<u8>]) -> Result<Vec<u8>, ()> {
|
|
|
|
let (head, tail) = values.split_first().unwrap();
|
|
|
|
let mut head = CboRoaringBitmapCodec::deserialize_from(head.as_slice()).unwrap();
|
|
|
|
|
|
|
|
for value in tail {
|
|
|
|
let bitmap = CboRoaringBitmapCodec::deserialize_from(value.as_slice()).unwrap();
|
|
|
|
head.union_with(&bitmap);
|
2020-08-04 21:19:21 +08:00
|
|
|
}
|
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
let mut vec = Vec::new();
|
|
|
|
CboRoaringBitmapCodec::serialize_into(&head, &mut vec).unwrap();
|
|
|
|
Ok(vec)
|
2020-08-04 21:19:21 +08:00
|
|
|
}
|
2020-07-07 22:48:49 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
fn documents_merge(key: &[u8], _values: &[Vec<u8>]) -> Result<Vec<u8>, ()> {
|
2020-10-04 23:31:12 +08:00
|
|
|
panic!("merging documents is an error ({:?})", key.as_bstr())
|
2020-10-04 19:17:58 +08:00
|
|
|
}
|
|
|
|
|
2020-10-05 00:40:34 +08:00
|
|
|
fn merge_readers(sources: Vec<Reader<Mmap>>, merge: MergeFn) -> Merger<Mmap, MergeFn> {
|
|
|
|
let mut builder = Merger::builder(merge);
|
|
|
|
builder.extend(sources);
|
|
|
|
builder.build()
|
|
|
|
}
|
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
fn merge_into_lmdb_database(
|
|
|
|
wtxn: &mut heed::RwTxn,
|
|
|
|
database: heed::PolyDatabase,
|
|
|
|
sources: Vec<Reader<Mmap>>,
|
|
|
|
merge: MergeFn,
|
|
|
|
) -> anyhow::Result<()> {
|
2020-08-04 21:19:21 +08:00
|
|
|
debug!("Merging {} MTBL stores...", sources.len());
|
|
|
|
let before = Instant::now();
|
2020-07-07 22:48:49 +08:00
|
|
|
|
2020-10-05 00:40:34 +08:00
|
|
|
let merger = merge_readers(sources, merge);
|
2020-10-04 19:17:58 +08:00
|
|
|
let mut in_iter = merger.into_merge_iter()?;
|
2020-10-05 00:40:34 +08:00
|
|
|
|
|
|
|
let mut out_iter = database.iter_mut::<_, ByteSlice, ByteSlice>(wtxn)?;
|
|
|
|
while let Some(result) = in_iter.next() {
|
|
|
|
let (k, v) = result?;
|
|
|
|
out_iter.append(k, v).with_context(|| format!("writing {:?} into LMDB", k.as_bstr()))?;
|
|
|
|
}
|
|
|
|
|
|
|
|
debug!("MTBL stores merged in {:.02?}!", before.elapsed());
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn write_into_lmdb_database(
|
|
|
|
wtxn: &mut heed::RwTxn,
|
|
|
|
database: heed::PolyDatabase,
|
|
|
|
reader: Reader<Mmap>,
|
|
|
|
) -> anyhow::Result<()> {
|
|
|
|
debug!("Writing MTBL stores...");
|
|
|
|
let before = Instant::now();
|
|
|
|
|
|
|
|
let mut in_iter = reader.into_iter()?;
|
2020-10-04 19:17:58 +08:00
|
|
|
let mut out_iter = database.iter_mut::<_, ByteSlice, ByteSlice>(wtxn)?;
|
|
|
|
while let Some(result) = in_iter.next() {
|
2020-08-04 21:19:21 +08:00
|
|
|
let (k, v) = result?;
|
2020-10-04 19:17:58 +08:00
|
|
|
out_iter.append(k, v).with_context(|| format!("writing {:?} into LMDB", k.as_bstr()))?;
|
2020-08-04 21:19:21 +08:00
|
|
|
}
|
2020-07-07 22:48:49 +08:00
|
|
|
|
2020-08-04 21:19:21 +08:00
|
|
|
debug!("MTBL stores merged in {:.02?}!", before.elapsed());
|
|
|
|
Ok(())
|
2020-07-07 22:48:49 +08:00
|
|
|
}
|
|
|
|
|
2020-09-21 20:59:48 +08:00
|
|
|
/// Returns the list of CSV sources that the indexer must read.
|
|
|
|
///
|
|
|
|
/// There is `num_threads` sources. If the file is not specified, the standard input is used.
|
|
|
|
fn csv_readers(
|
|
|
|
csv_file_path: Option<PathBuf>,
|
2020-07-07 17:32:33 +08:00
|
|
|
num_threads: usize,
|
2020-09-21 20:59:48 +08:00
|
|
|
) -> anyhow::Result<Vec<csv::Reader<Box<dyn Read + Send>>>>
|
2020-07-01 23:49:46 +08:00
|
|
|
{
|
2020-09-21 20:59:48 +08:00
|
|
|
match csv_file_path {
|
|
|
|
Some(file_path) => {
|
|
|
|
// We open the file # jobs times.
|
|
|
|
iter::repeat_with(|| {
|
|
|
|
let file = File::open(&file_path)
|
|
|
|
.with_context(|| format!("Failed to read CSV file {}", file_path.display()))?;
|
|
|
|
// if the file extension is "gz" or "gzip" we can decode and read it.
|
|
|
|
let r = if file_path.extension().map_or(false, |e| e == "gz" || e == "gzip") {
|
|
|
|
Box::new(GzDecoder::new(file)) as Box<dyn Read + Send>
|
|
|
|
} else {
|
|
|
|
Box::new(file) as Box<dyn Read + Send>
|
|
|
|
};
|
|
|
|
Ok(csv::Reader::from_reader(r)) as anyhow::Result<_>
|
|
|
|
})
|
|
|
|
.take(num_threads)
|
|
|
|
.collect()
|
|
|
|
},
|
|
|
|
None => {
|
|
|
|
let mut csv_readers = Vec::new();
|
|
|
|
let mut writers = Vec::new();
|
|
|
|
for (r, w) in iter::repeat_with(ringtail::io::pipe).take(num_threads) {
|
|
|
|
let r = Box::new(r) as Box<dyn Read + Send>;
|
|
|
|
csv_readers.push(csv::Reader::from_reader(r));
|
|
|
|
writers.push(w);
|
2020-08-29 16:56:40 +08:00
|
|
|
}
|
2020-07-02 04:45:43 +08:00
|
|
|
|
2020-09-21 20:59:48 +08:00
|
|
|
thread::spawn(move || {
|
|
|
|
let stdin = std::io::stdin();
|
|
|
|
let mut stdin = stdin.lock();
|
|
|
|
let mut buffer = [0u8; 4096];
|
|
|
|
loop {
|
|
|
|
match stdin.read(&mut buffer)? {
|
|
|
|
0 => return Ok(()) as io::Result<()>,
|
|
|
|
size => for w in &mut writers {
|
|
|
|
w.write_all(&buffer[..size])?;
|
|
|
|
}
|
|
|
|
}
|
2020-08-29 16:56:40 +08:00
|
|
|
}
|
2020-09-21 20:59:48 +08:00
|
|
|
});
|
2020-05-26 02:39:53 +08:00
|
|
|
|
2020-09-21 20:59:48 +08:00
|
|
|
Ok(csv_readers)
|
|
|
|
},
|
2020-07-07 17:32:33 +08:00
|
|
|
}
|
2020-05-26 02:39:53 +08:00
|
|
|
}
|
|
|
|
|
2020-07-02 04:45:43 +08:00
|
|
|
fn main() -> anyhow::Result<()> {
|
|
|
|
let opt = Opt::from_args();
|
2020-06-29 19:54:47 +08:00
|
|
|
|
2020-07-12 17:04:35 +08:00
|
|
|
stderrlog::new()
|
|
|
|
.verbosity(opt.verbose)
|
|
|
|
.show_level(false)
|
|
|
|
.timestamp(stderrlog::Timestamp::Off)
|
|
|
|
.init()?;
|
|
|
|
|
2020-06-28 18:13:10 +08:00
|
|
|
if let Some(jobs) = opt.jobs {
|
|
|
|
rayon::ThreadPoolBuilder::new().num_threads(jobs).build_global()?;
|
|
|
|
}
|
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
if opt.database.exists() {
|
|
|
|
bail!("Database ({}) already exists, delete it to continue.", opt.database.display());
|
|
|
|
}
|
|
|
|
|
2020-07-04 18:34:10 +08:00
|
|
|
std::fs::create_dir_all(&opt.database)?;
|
2020-07-07 17:32:33 +08:00
|
|
|
let env = EnvOpenOptions::new()
|
2020-08-10 19:53:53 +08:00
|
|
|
.map_size(opt.database_size)
|
2020-07-07 17:32:33 +08:00
|
|
|
.max_dbs(10)
|
2020-08-07 19:11:31 +08:00
|
|
|
.open(&opt.database)?;
|
2020-06-29 19:54:47 +08:00
|
|
|
|
2020-08-28 21:38:05 +08:00
|
|
|
let before_indexing = Instant::now();
|
|
|
|
let index = Index::new(&env)?;
|
2020-06-29 19:54:47 +08:00
|
|
|
|
2020-07-07 17:32:33 +08:00
|
|
|
let num_threads = rayon::current_num_threads();
|
2020-09-23 20:50:52 +08:00
|
|
|
let linked_hash_map_size = opt.indexer.linked_hash_map_size;
|
2020-08-21 22:41:26 +08:00
|
|
|
let max_nb_chunks = opt.indexer.max_nb_chunks;
|
|
|
|
let max_memory = opt.indexer.max_memory;
|
|
|
|
let chunk_compression_type = compression_type_from_str(&opt.indexer.chunk_compression_type);
|
|
|
|
let chunk_compression_level = opt.indexer.chunk_compression_level;
|
2020-09-29 21:10:08 +08:00
|
|
|
let log_every_n = opt.indexer.log_every_n;
|
2020-08-05 18:10:41 +08:00
|
|
|
|
2020-09-21 20:59:48 +08:00
|
|
|
let readers = csv_readers(opt.csv_file, num_threads)?
|
2020-07-07 18:21:22 +08:00
|
|
|
.into_par_iter()
|
2020-07-07 17:32:33 +08:00
|
|
|
.enumerate()
|
2020-08-21 22:41:26 +08:00
|
|
|
.map(|(i, rdr)| {
|
2020-09-27 17:46:52 +08:00
|
|
|
let store = Store::new(
|
2020-09-23 20:50:52 +08:00
|
|
|
linked_hash_map_size,
|
2020-08-21 22:41:26 +08:00
|
|
|
max_nb_chunks,
|
2020-09-23 17:54:41 +08:00
|
|
|
Some(max_memory),
|
2020-08-21 22:41:26 +08:00
|
|
|
chunk_compression_type,
|
|
|
|
chunk_compression_level,
|
2020-09-27 17:46:52 +08:00
|
|
|
)?;
|
2020-09-29 21:10:08 +08:00
|
|
|
store.index_csv(rdr, i, num_threads, log_every_n)
|
2020-08-21 22:41:26 +08:00
|
|
|
})
|
2020-08-07 19:11:31 +08:00
|
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
|
|
|
2020-10-05 00:40:34 +08:00
|
|
|
let mut main_readers = Vec::with_capacity(readers.len());
|
|
|
|
let mut word_docids_readers = Vec::with_capacity(readers.len());
|
|
|
|
let mut docid_word_positions_readers = Vec::with_capacity(readers.len());
|
|
|
|
let mut words_pairs_proximities_docids_readers = Vec::with_capacity(readers.len());
|
|
|
|
let mut documents_readers = Vec::with_capacity(readers.len());
|
2020-10-04 19:17:58 +08:00
|
|
|
readers.into_iter().for_each(|readers| {
|
2020-10-05 00:40:34 +08:00
|
|
|
main_readers.push(readers.main);
|
|
|
|
word_docids_readers.push(readers.word_docids);
|
|
|
|
docid_word_positions_readers.push(readers.docid_word_positions);
|
|
|
|
words_pairs_proximities_docids_readers.push(readers.words_pairs_proximities_docids);
|
|
|
|
documents_readers.push(readers.documents);
|
2020-08-07 19:11:31 +08:00
|
|
|
});
|
2020-07-02 04:45:43 +08:00
|
|
|
|
2020-10-05 00:40:34 +08:00
|
|
|
let merge_readers = |readers, merge| {
|
|
|
|
let mut writer = tempfile().map(|f| {
|
|
|
|
create_writer(chunk_compression_type, chunk_compression_level, f)
|
|
|
|
})?;
|
|
|
|
let merger = merge_readers(readers, merge);
|
|
|
|
merger.write_into(&mut writer)?;
|
|
|
|
writer_into_reader(writer)
|
|
|
|
};
|
|
|
|
|
|
|
|
debug!("Merging the main, word docids and words pairs proximity docids in parallel...");
|
|
|
|
let (main, (word_docids, words_pairs_proximities_docids)) = rayon::join(move || {
|
|
|
|
merge_readers(main_readers, main_merge)
|
|
|
|
}, || rayon::join(|| {
|
|
|
|
merge_readers(word_docids_readers, word_docids_merge)
|
|
|
|
}, || {
|
|
|
|
merge_readers(words_pairs_proximities_docids_readers, words_pairs_proximities_docids_merge)
|
|
|
|
}));
|
|
|
|
|
|
|
|
let main = main?;
|
|
|
|
let word_docids = word_docids?;
|
|
|
|
let words_pairs_proximities_docids = words_pairs_proximities_docids?;
|
|
|
|
|
2020-08-28 21:38:05 +08:00
|
|
|
let mut wtxn = env.write_txn()?;
|
2020-08-29 21:14:04 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
debug!("Writing the main elements into LMDB on disk...");
|
2020-10-05 00:40:34 +08:00
|
|
|
write_into_lmdb_database(&mut wtxn, index.main, main)?;
|
2020-10-04 19:17:58 +08:00
|
|
|
|
|
|
|
debug!("Writing the words docids into LMDB on disk...");
|
|
|
|
let db = *index.word_docids.as_polymorph();
|
2020-10-05 00:40:34 +08:00
|
|
|
write_into_lmdb_database(&mut wtxn, db, word_docids)?;
|
2020-10-04 19:17:58 +08:00
|
|
|
|
|
|
|
debug!("Writing the docid word positions into LMDB on disk...");
|
|
|
|
let db = *index.docid_word_positions.as_polymorph();
|
2020-10-05 00:40:34 +08:00
|
|
|
merge_into_lmdb_database(&mut wtxn, db, docid_word_positions_readers, docid_word_positions_merge)?;
|
2020-10-04 19:17:58 +08:00
|
|
|
|
|
|
|
debug!("Writing the words pairs proximities docids into LMDB on disk...");
|
|
|
|
let db = *index.word_pair_proximity_docids.as_polymorph();
|
2020-10-05 00:40:34 +08:00
|
|
|
write_into_lmdb_database(&mut wtxn, db, words_pairs_proximities_docids)?;
|
2020-08-29 21:14:04 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
debug!("Writing the documents into LMDB on disk...");
|
|
|
|
let db = *index.documents.as_polymorph();
|
2020-10-05 00:40:34 +08:00
|
|
|
merge_into_lmdb_database(&mut wtxn, db, documents_readers, documents_merge)?;
|
2020-08-29 21:14:04 +08:00
|
|
|
|
2020-10-04 19:17:58 +08:00
|
|
|
debug!("Retrieving the number of documents...");
|
2020-08-28 21:38:05 +08:00
|
|
|
let count = index.number_of_documents(&wtxn)?;
|
2020-08-29 21:14:04 +08:00
|
|
|
|
2020-08-28 21:38:05 +08:00
|
|
|
wtxn.commit()?;
|
|
|
|
|
|
|
|
info!("Wrote {} documents in {:.02?}", count, before_indexing.elapsed());
|
2020-05-26 02:39:53 +08:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|