2020-05-30 19:56:57 +02:00
|
|
|
use std::collections::hash_map::Entry;
|
2020-05-25 20:39:53 +02:00
|
|
|
use std::collections::{HashMap, BTreeSet};
|
|
|
|
use std::convert::TryFrom;
|
|
|
|
use std::fs::File;
|
|
|
|
use std::hash::BuildHasherDefault;
|
|
|
|
use std::path::PathBuf;
|
2020-05-26 12:18:29 +02:00
|
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
2020-05-25 20:39:53 +02:00
|
|
|
|
|
|
|
use anyhow::{ensure, Context};
|
2020-05-30 15:35:33 +02:00
|
|
|
use roaring::RoaringBitmap;
|
2020-05-25 20:39:53 +02:00
|
|
|
use fst::IntoStreamer;
|
|
|
|
use fxhash::FxHasher32;
|
2020-05-30 19:56:57 +02:00
|
|
|
use heed::{EnvOpenOptions, PolyDatabase, Database};
|
2020-05-30 15:35:33 +02:00
|
|
|
use heed::types::*;
|
2020-05-25 20:39:53 +02:00
|
|
|
use rayon::prelude::*;
|
|
|
|
use slice_group_by::StrGroupBy;
|
|
|
|
use structopt::StructOpt;
|
|
|
|
|
|
|
|
pub type FastMap4<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher32>>;
|
|
|
|
pub type SmallString32 = smallstr::SmallString<[u8; 32]>;
|
2020-05-30 15:35:33 +02:00
|
|
|
pub type BEU32 = heed::zerocopy::U32<heed::byteorder::BE>;
|
|
|
|
pub type DocumentId = u32;
|
2020-05-25 20:39:53 +02:00
|
|
|
|
|
|
|
#[cfg(target_os = "linux")]
|
|
|
|
#[global_allocator]
|
|
|
|
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
|
|
|
|
|
2020-05-30 15:35:33 +02:00
|
|
|
static ID_GENERATOR: AtomicUsize = AtomicUsize::new(0); // AtomicU32 ?
|
2020-05-26 12:18:29 +02:00
|
|
|
|
2020-05-25 20:39:53 +02:00
|
|
|
#[derive(Debug, StructOpt)]
|
|
|
|
#[structopt(name = "mm-indexer", about = "The server side of the daugt project.")]
|
|
|
|
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,
|
|
|
|
|
|
|
|
/// Files to index in parallel.
|
|
|
|
files_to_index: Vec<PathBuf>,
|
|
|
|
}
|
|
|
|
|
2020-05-30 15:35:33 +02:00
|
|
|
fn union_postings_ids(_key: &[u8], old_value: Option<&[u8]>, new_value: RoaringBitmap) -> Option<Vec<u8>> {
|
|
|
|
let result = match old_value {
|
|
|
|
Some(bytes) => {
|
|
|
|
let mut old_value = RoaringBitmap::deserialize_from(bytes).unwrap();
|
|
|
|
old_value.union_with(&new_value);
|
|
|
|
old_value
|
2020-05-26 17:41:44 +02:00
|
|
|
},
|
2020-05-30 15:35:33 +02:00
|
|
|
None => new_value,
|
|
|
|
};
|
2020-05-25 20:39:53 +02:00
|
|
|
|
2020-05-30 15:35:33 +02:00
|
|
|
let mut vec = Vec::new();
|
|
|
|
result.serialize_into(&mut vec).unwrap();
|
|
|
|
Some(vec)
|
2020-05-25 20:39:53 +02:00
|
|
|
}
|
|
|
|
|
2020-05-30 15:35:33 +02:00
|
|
|
fn union_words_fst(key: &[u8], old_value: Option<&[u8]>, new_value: &fst::Set<Vec<u8>>) -> Option<Vec<u8>> {
|
2020-05-25 20:39:53 +02:00
|
|
|
if key != b"words-fst" { unimplemented!() }
|
|
|
|
|
2020-05-26 12:18:29 +02:00
|
|
|
// Do an union of the old and the new set of words.
|
|
|
|
let mut builder = fst::set::OpBuilder::new();
|
2020-05-25 20:39:53 +02:00
|
|
|
|
2020-05-26 12:18:29 +02:00
|
|
|
let old_words = old_value.map(|v| fst::Set::new(v).unwrap());
|
|
|
|
let old_words = old_words.as_ref().map(|v| v.into_stream());
|
|
|
|
if let Some(old_words) = old_words {
|
|
|
|
builder.push(old_words);
|
|
|
|
}
|
2020-05-25 20:39:53 +02:00
|
|
|
|
2020-05-30 15:35:33 +02:00
|
|
|
builder.push(new_value);
|
2020-05-26 12:18:29 +02:00
|
|
|
|
|
|
|
let op = builder.r#union();
|
2020-05-25 20:39:53 +02:00
|
|
|
let mut build = fst::SetBuilder::memory();
|
|
|
|
build.extend_stream(op.into_stream()).unwrap();
|
|
|
|
|
|
|
|
Some(build.into_inner().unwrap())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn alphanumeric_tokens(string: &str) -> impl Iterator<Item = &str> {
|
|
|
|
let is_alphanumeric = |s: &&str| s.chars().next().map_or(false, char::is_alphanumeric);
|
|
|
|
string.linear_group_by_key(|c| c.is_alphanumeric()).filter(is_alphanumeric)
|
|
|
|
}
|
|
|
|
|
2020-05-30 19:56:57 +02:00
|
|
|
#[derive(Default)]
|
|
|
|
struct Indexed {
|
|
|
|
fst: fst::Set<Vec<u8>>,
|
|
|
|
postings_ids: FastMap4<SmallString32, RoaringBitmap>,
|
|
|
|
headers: Vec<u8>,
|
|
|
|
documents: Vec<(DocumentId, Vec<u8>)>,
|
2020-05-30 15:35:33 +02:00
|
|
|
}
|
|
|
|
|
2020-05-30 19:56:57 +02:00
|
|
|
impl Indexed {
|
|
|
|
fn merge_with(mut self, mut other: Indexed) -> Indexed {
|
|
|
|
|
|
|
|
// Union of the two FSTs
|
|
|
|
let op = fst::set::OpBuilder::new()
|
|
|
|
.add(self.fst.into_stream())
|
|
|
|
.add(other.fst.into_stream())
|
|
|
|
.r#union();
|
|
|
|
|
|
|
|
let mut build = fst::SetBuilder::memory();
|
|
|
|
build.extend_stream(op.into_stream()).unwrap();
|
|
|
|
let fst = build.into_set();
|
|
|
|
|
|
|
|
// Merge the postings by unions
|
|
|
|
for (word, mut postings) in other.postings_ids {
|
|
|
|
match self.postings_ids.entry(word) {
|
|
|
|
Entry::Occupied(mut entry) => {
|
|
|
|
let old = entry.get();
|
|
|
|
postings.union_with(&old);
|
|
|
|
entry.insert(postings);
|
|
|
|
},
|
|
|
|
Entry::Vacant(entry) => {
|
|
|
|
entry.insert(postings);
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2020-05-30 15:35:33 +02:00
|
|
|
|
2020-05-30 19:56:57 +02:00
|
|
|
// assert headers are valid
|
2020-05-31 12:29:19 +02:00
|
|
|
if !self.headers.is_empty() {
|
|
|
|
assert_eq!(self.headers, other.headers);
|
|
|
|
}
|
2020-05-30 15:35:33 +02:00
|
|
|
|
2020-05-30 19:56:57 +02:00
|
|
|
// extend the documents
|
|
|
|
self.documents.append(&mut other.documents);
|
2020-05-30 15:35:33 +02:00
|
|
|
|
2020-05-30 19:56:57 +02:00
|
|
|
Indexed {
|
|
|
|
fst,
|
|
|
|
postings_ids: self.postings_ids,
|
|
|
|
headers: self.headers,
|
|
|
|
documents: self.documents,
|
2020-05-30 15:35:33 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-31 12:29:19 +02:00
|
|
|
fn index_csv(mut rdr: csv::Reader<File>) -> anyhow::Result<Indexed> {
|
2020-05-25 20:39:53 +02:00
|
|
|
const MAX_POSITION: usize = 1000;
|
|
|
|
const MAX_ATTRIBUTES: usize = u32::max_value() as usize / MAX_POSITION;
|
|
|
|
|
|
|
|
let mut document = csv::StringRecord::new();
|
2020-05-30 19:56:57 +02:00
|
|
|
let mut postings_ids = FastMap4::default();
|
|
|
|
let mut documents = Vec::new();
|
2020-05-25 20:39:53 +02:00
|
|
|
|
|
|
|
// Write the headers into a Vec of bytes.
|
|
|
|
let headers = rdr.headers()?;
|
|
|
|
let mut writer = csv::WriterBuilder::new().has_headers(false).from_writer(Vec::new());
|
|
|
|
writer.write_byte_record(headers.as_byte_record())?;
|
|
|
|
let headers = writer.into_inner()?;
|
|
|
|
|
|
|
|
while rdr.read_record(&mut document)? {
|
2020-05-26 12:18:29 +02:00
|
|
|
let document_id = ID_GENERATOR.fetch_add(1, Ordering::SeqCst);
|
2020-05-30 15:35:33 +02:00
|
|
|
let document_id = DocumentId::try_from(document_id).context("Generated id is too big")?;
|
2020-05-25 20:39:53 +02:00
|
|
|
|
|
|
|
for (_attr, content) in document.iter().enumerate().take(MAX_ATTRIBUTES) {
|
|
|
|
for (_pos, word) in alphanumeric_tokens(&content).enumerate().take(MAX_POSITION) {
|
2020-05-30 15:35:33 +02:00
|
|
|
if !word.is_empty() && word.len() < 500 { // LMDB limits
|
2020-05-30 19:56:57 +02:00
|
|
|
postings_ids.entry(SmallString32::from(word))
|
2020-05-30 15:35:33 +02:00
|
|
|
.or_insert_with(RoaringBitmap::new)
|
|
|
|
.insert(document_id);
|
|
|
|
}
|
2020-05-25 20:39:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// We write the document in the database.
|
|
|
|
let mut writer = csv::WriterBuilder::new().has_headers(false).from_writer(Vec::new());
|
|
|
|
writer.write_byte_record(document.as_byte_record())?;
|
|
|
|
let document = writer.into_inner()?;
|
2020-05-30 19:56:57 +02:00
|
|
|
documents.push((document_id, document));
|
2020-05-25 20:39:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// We compute and store the postings list into the DB.
|
2020-05-30 19:56:57 +02:00
|
|
|
let mut new_words = BTreeSet::default();
|
|
|
|
for (word, _new_ids) in &postings_ids {
|
|
|
|
new_words.insert(word.clone());
|
2020-05-25 20:39:53 +02:00
|
|
|
}
|
|
|
|
|
2020-05-30 19:56:57 +02:00
|
|
|
let new_words_fst = fst::Set::from_iter(new_words.iter().map(SmallString32::as_str))?;
|
|
|
|
|
|
|
|
Ok(Indexed { fst: new_words_fst, headers, postings_ids, documents })
|
|
|
|
}
|
|
|
|
|
|
|
|
fn writer(
|
|
|
|
wtxn: &mut heed::RwTxn,
|
|
|
|
main: PolyDatabase,
|
|
|
|
postings_ids: Database<Str, ByteSlice>,
|
|
|
|
documents: Database<OwnedType<BEU32>, ByteSlice>,
|
|
|
|
indexed: Indexed,
|
|
|
|
) -> anyhow::Result<usize>
|
|
|
|
{
|
|
|
|
// Write and merge the words fst
|
|
|
|
let old_value = main.get::<_, Str, ByteSlice>(wtxn, "words-fst")?;
|
|
|
|
let new_value = union_words_fst(b"words-fst", old_value, &indexed.fst)
|
|
|
|
.context("error while do a words-fst union")?;
|
|
|
|
main.put::<_, Str, ByteSlice>(wtxn, "words-fst", &new_value)?;
|
|
|
|
|
|
|
|
// Write and merge the headers
|
|
|
|
if let Some(old_headers) = main.get::<_, Str, ByteSlice>(wtxn, "headers")? {
|
|
|
|
ensure!(old_headers == &*indexed.headers, "headers differs from the previous ones");
|
|
|
|
}
|
|
|
|
main.put::<_, Str, ByteSlice>(wtxn, "headers", &indexed.headers)?;
|
|
|
|
|
|
|
|
// Write and merge the postings lists
|
|
|
|
for (word, postings) in indexed.postings_ids {
|
|
|
|
let old_value = postings_ids.get(wtxn, word.as_str())?;
|
|
|
|
let new_value = union_postings_ids(word.as_bytes(), old_value, postings)
|
|
|
|
.context("error while do a words-fst union")?;
|
|
|
|
postings_ids.put(wtxn, &word, &new_value)?;
|
|
|
|
}
|
2020-05-25 20:39:53 +02:00
|
|
|
|
2020-05-30 19:56:57 +02:00
|
|
|
let count = indexed.documents.len();
|
2020-05-25 20:39:53 +02:00
|
|
|
|
2020-05-30 19:56:57 +02:00
|
|
|
// Write the documents
|
|
|
|
for (id, content) in indexed.documents {
|
|
|
|
documents.put(wtxn, &BEU32::new(id), &content)?;
|
|
|
|
}
|
2020-05-25 20:39:53 +02:00
|
|
|
|
2020-05-30 19:56:57 +02:00
|
|
|
Ok(count)
|
2020-05-25 20:39:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() -> anyhow::Result<()> {
|
|
|
|
let opt = Opt::from_args();
|
|
|
|
|
2020-05-30 15:35:33 +02:00
|
|
|
std::fs::create_dir_all(&opt.database)?;
|
|
|
|
let env = EnvOpenOptions::new()
|
|
|
|
.map_size(100 * 1024 * 1024 * 1024) // 100 GB
|
|
|
|
.max_readers(10)
|
|
|
|
.max_dbs(5)
|
|
|
|
.open(opt.database)?;
|
2020-05-26 12:18:29 +02:00
|
|
|
|
2020-05-30 19:56:57 +02:00
|
|
|
let main = env.create_poly_database(None)?;
|
|
|
|
let postings_ids: Database<Str, ByteSlice> = env.create_database(Some("postings-ids"))?;
|
|
|
|
let documents: Database<OwnedType<BEU32>, ByteSlice> = env.create_database(Some("documents"))?;
|
2020-05-25 20:39:53 +02:00
|
|
|
|
|
|
|
let res = opt.files_to_index
|
|
|
|
.into_par_iter()
|
2020-05-31 12:29:19 +02:00
|
|
|
.try_fold(|| Indexed::default(), |acc, path| {
|
2020-05-25 20:39:53 +02:00
|
|
|
let rdr = csv::Reader::from_path(path)?;
|
2020-05-31 12:29:19 +02:00
|
|
|
let indexed = index_csv(rdr)?;
|
2020-05-30 19:56:57 +02:00
|
|
|
Ok(acc.merge_with(indexed)) as anyhow::Result<Indexed>
|
|
|
|
})
|
|
|
|
.map(|indexed| match indexed {
|
|
|
|
Ok(indexed) => {
|
2020-05-31 12:29:19 +02:00
|
|
|
let tid = rayon::current_thread_index();
|
|
|
|
eprintln!("{:?}: A new step to write into LMDB", tid);
|
2020-05-30 19:56:57 +02:00
|
|
|
let mut wtxn = env.write_txn()?;
|
|
|
|
let count = writer(&mut wtxn, main, postings_ids, documents, indexed)?;
|
|
|
|
wtxn.commit()?;
|
2020-05-31 12:29:19 +02:00
|
|
|
eprintln!("{:?}: Wrote {} documents into LMDB", tid, count);
|
2020-05-30 19:56:57 +02:00
|
|
|
Ok(count)
|
|
|
|
},
|
|
|
|
Err(e) => Err(e),
|
2020-05-25 20:39:53 +02:00
|
|
|
})
|
2020-05-31 12:29:19 +02:00
|
|
|
.inspect(|_| {
|
|
|
|
eprintln!("Total number of documents seen so far is {}", ID_GENERATOR.load(Ordering::Relaxed))
|
|
|
|
})
|
2020-05-25 20:39:53 +02:00
|
|
|
.try_reduce(|| 0, |a, b| Ok(a + b));
|
|
|
|
|
2020-05-30 15:35:33 +02:00
|
|
|
println!("indexed {:?} documents", res);
|
2020-05-25 20:39:53 +02:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|