2020-06-09 00:05:14 +08:00
|
|
|
mod best_proximity;
|
2020-06-22 23:56:07 +08:00
|
|
|
mod heed_codec;
|
2020-06-14 18:51:54 +08:00
|
|
|
mod iter_shortest_paths;
|
2020-06-05 15:48:46 +08:00
|
|
|
mod query_tokens;
|
2020-06-05 02:25:51 +08:00
|
|
|
|
|
|
|
use std::borrow::Cow;
|
2020-05-31 22:09:34 +08:00
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::hash::BuildHasherDefault;
|
2020-06-11 03:35:01 +08:00
|
|
|
use std::time::Instant;
|
2020-05-31 22:09:34 +08:00
|
|
|
|
2020-05-31 23:48:13 +08:00
|
|
|
use cow_utils::CowUtils;
|
|
|
|
use fst::{IntoStreamer, Streamer};
|
2020-05-31 22:09:34 +08:00
|
|
|
use fxhash::FxHasher32;
|
2020-05-31 23:48:13 +08:00
|
|
|
use heed::types::*;
|
|
|
|
use heed::{PolyDatabase, Database};
|
2020-06-01 00:21:24 +08:00
|
|
|
use levenshtein_automata::LevenshteinAutomatonBuilder as LevBuilder;
|
2020-06-05 22:32:14 +08:00
|
|
|
use once_cell::sync::Lazy;
|
2020-05-31 23:48:13 +08:00
|
|
|
use roaring::RoaringBitmap;
|
2020-06-05 02:25:51 +08:00
|
|
|
|
2020-06-09 00:05:14 +08:00
|
|
|
use self::best_proximity::BestProximity;
|
2020-06-22 23:56:07 +08:00
|
|
|
use self::heed_codec::RoaringBitmapCodec;
|
|
|
|
use self::query_tokens::{QueryTokens, QueryToken};
|
2020-05-31 22:09:34 +08:00
|
|
|
|
2020-06-05 22:32:14 +08:00
|
|
|
// Building these factories is not free.
|
|
|
|
static LEVDIST0: Lazy<LevBuilder> = Lazy::new(|| LevBuilder::new(0, true));
|
|
|
|
static LEVDIST1: Lazy<LevBuilder> = Lazy::new(|| LevBuilder::new(1, true));
|
|
|
|
static LEVDIST2: Lazy<LevBuilder> = Lazy::new(|| LevBuilder::new(2, true));
|
2020-06-01 00:21:24 +08:00
|
|
|
|
2020-05-31 22:09:34 +08:00
|
|
|
pub type FastMap4<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher32>>;
|
|
|
|
pub type SmallString32 = smallstr::SmallString<[u8; 32]>;
|
2020-06-11 17:55:03 +08:00
|
|
|
pub type SmallVec32<T> = smallvec::SmallVec<[T; 32]>;
|
|
|
|
pub type SmallVec16<T> = smallvec::SmallVec<[T; 16]>;
|
2020-05-31 22:09:34 +08:00
|
|
|
pub type BEU32 = heed::zerocopy::U32<heed::byteorder::BE>;
|
|
|
|
pub type DocumentId = u32;
|
2020-06-05 22:32:14 +08:00
|
|
|
pub type AttributeId = u32;
|
2020-05-31 22:09:34 +08:00
|
|
|
|
2020-05-31 23:48:13 +08:00
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct Index {
|
2020-06-23 00:02:22 +08:00
|
|
|
/// Contains many different types (e.g. the documents CSV headers).
|
2020-05-31 23:48:13 +08:00
|
|
|
pub main: PolyDatabase,
|
2020-06-23 00:02:22 +08:00
|
|
|
/// A word and all the positions where it appears in the whole dataset.
|
|
|
|
pub word_positions: Database<Str, RoaringBitmapCodec>,
|
|
|
|
pub prefix_word_positions: Database<Str, RoaringBitmapCodec>,
|
|
|
|
/// Maps a word at a position (u32) and all the documents ids where it appears.
|
|
|
|
pub word_position_docids: Database<ByteSlice, RoaringBitmapCodec>,
|
|
|
|
pub prefix_word_position_docids: Database<ByteSlice, RoaringBitmapCodec>,
|
2020-06-23 01:04:10 +08:00
|
|
|
/// Maps a word and an attribute (u32) to all the documents ids that it appears in.
|
|
|
|
pub word_attribute_docids: Database<ByteSlice, RoaringBitmapCodec>,
|
2020-06-23 00:02:22 +08:00
|
|
|
/// Maps an internal document to the content of the document in CSV.
|
2020-05-31 23:48:13 +08:00
|
|
|
pub documents: Database<OwnedType<BEU32>, ByteSlice>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Index {
|
|
|
|
pub fn new(env: &heed::Env) -> heed::Result<Index> {
|
2020-06-23 00:02:22 +08:00
|
|
|
Ok(Index {
|
|
|
|
main: env.create_poly_database(None)?,
|
|
|
|
word_positions: env.create_database(Some("word-positions"))?,
|
|
|
|
prefix_word_positions: env.create_database(Some("prefix-word-positions"))?,
|
|
|
|
word_position_docids: env.create_database(Some("word-position-docids"))?,
|
|
|
|
prefix_word_position_docids: env.create_database(Some("prefix-word-position-docids"))?,
|
2020-06-23 01:04:10 +08:00
|
|
|
word_attribute_docids: env.create_database(Some("word-attribute-docids"))?,
|
2020-06-23 00:02:22 +08:00
|
|
|
documents: env.create_database(Some("documents"))?,
|
|
|
|
})
|
2020-05-31 23:48:13 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn headers<'t>(&self, rtxn: &'t heed::RoTxn) -> heed::Result<Option<&'t [u8]>> {
|
|
|
|
self.main.get::<_, Str, ByteSlice>(rtxn, "headers")
|
|
|
|
}
|
|
|
|
|
2020-06-23 01:04:10 +08:00
|
|
|
pub fn fst<'t>(&self, rtxn: &'t heed::RoTxn) -> anyhow::Result<Option<fst::Set<&'t [u8]>>> {
|
|
|
|
match self.main.get::<_, Str, ByteSlice>(rtxn, "words-fst")? {
|
|
|
|
Some(bytes) => Ok(Some(fst::Set::new(bytes)?)),
|
|
|
|
None => Ok(None),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-31 23:48:13 +08:00
|
|
|
pub fn search(&self, rtxn: &heed::RoTxn, query: &str) -> anyhow::Result<Vec<DocumentId>> {
|
2020-06-23 01:04:10 +08:00
|
|
|
let fst = match self.fst(rtxn)? {
|
|
|
|
Some(fst) => fst,
|
|
|
|
None => return Ok(vec![]),
|
2020-05-31 23:48:13 +08:00
|
|
|
};
|
|
|
|
|
2020-06-05 22:32:14 +08:00
|
|
|
let (lev0, lev1, lev2) = (&LEVDIST0, &LEVDIST1, &LEVDIST2);
|
2020-05-31 23:48:13 +08:00
|
|
|
|
2020-06-05 15:48:46 +08:00
|
|
|
let words: Vec<_> = QueryTokens::new(query).collect();
|
2020-06-05 00:36:30 +08:00
|
|
|
let ends_with_whitespace = query.chars().last().map_or(false, char::is_whitespace);
|
2020-05-31 23:48:13 +08:00
|
|
|
let number_of_words = words.len();
|
2020-06-06 02:12:52 +08:00
|
|
|
let dfas = words.into_iter().enumerate().map(|(i, word)| {
|
2020-06-05 02:25:51 +08:00
|
|
|
let (word, quoted) = match word {
|
2020-06-05 15:48:46 +08:00
|
|
|
QueryToken::Free(word) => (word.cow_to_lowercase(), false),
|
|
|
|
QueryToken::Quoted(word) => (Cow::Borrowed(word), true),
|
2020-06-05 02:25:51 +08:00
|
|
|
};
|
2020-05-31 23:48:13 +08:00
|
|
|
let is_last = i + 1 == number_of_words;
|
2020-06-05 02:25:51 +08:00
|
|
|
let is_prefix = is_last && !ends_with_whitespace && !quoted;
|
2020-06-05 22:32:14 +08:00
|
|
|
let lev = match word.len() {
|
|
|
|
0..=4 => if quoted { lev0 } else { lev0 },
|
|
|
|
5..=8 => if quoted { lev0 } else { lev1 },
|
|
|
|
_ => if quoted { lev0 } else { lev2 },
|
2020-05-31 23:48:13 +08:00
|
|
|
};
|
|
|
|
|
2020-06-05 22:32:14 +08:00
|
|
|
let dfa = if is_prefix {
|
|
|
|
lev.build_prefix_dfa(&word)
|
|
|
|
} else {
|
|
|
|
lev.build_dfa(&word)
|
|
|
|
};
|
|
|
|
|
|
|
|
(word, is_prefix, dfa)
|
2020-06-06 02:12:52 +08:00
|
|
|
});
|
|
|
|
|
2020-06-11 17:55:03 +08:00
|
|
|
let mut words = Vec::new();
|
2020-06-09 00:05:14 +08:00
|
|
|
let mut positions = Vec::new();
|
2020-06-11 03:35:01 +08:00
|
|
|
let before = Instant::now();
|
2020-06-09 00:05:14 +08:00
|
|
|
|
2020-06-11 17:55:03 +08:00
|
|
|
for (word, _is_prefix, dfa) in dfas {
|
2020-06-20 19:25:42 +08:00
|
|
|
let before = Instant::now();
|
|
|
|
|
2020-06-06 02:12:52 +08:00
|
|
|
let mut count = 0;
|
|
|
|
let mut union_positions = RoaringBitmap::default();
|
2020-06-11 17:55:03 +08:00
|
|
|
let mut derived_words = Vec::new();
|
|
|
|
// TODO re-enable the prefixes system
|
|
|
|
let mut stream = fst.search(&dfa).into_stream();
|
|
|
|
while let Some(word) = stream.next() {
|
|
|
|
let word = std::str::from_utf8(word)?;
|
2020-06-23 00:02:22 +08:00
|
|
|
if let Some(right) = self.word_positions.get(rtxn, word)? {
|
2020-06-06 02:12:52 +08:00
|
|
|
union_positions.union_with(&right);
|
2020-06-16 18:58:29 +08:00
|
|
|
derived_words.push((word.as_bytes().to_vec(), right));
|
2020-06-11 17:55:03 +08:00
|
|
|
count += 1;
|
2020-06-01 00:20:49 +08:00
|
|
|
}
|
2020-06-05 22:32:14 +08:00
|
|
|
}
|
|
|
|
|
2020-06-20 19:25:42 +08:00
|
|
|
eprintln!("{} words for {:?} we have found positions {:?} in {:.02?}",
|
|
|
|
count, word, union_positions, before.elapsed());
|
2020-06-11 17:55:03 +08:00
|
|
|
words.push(derived_words);
|
2020-06-09 00:05:14 +08:00
|
|
|
positions.push(union_positions.iter().collect());
|
2020-06-05 22:32:14 +08:00
|
|
|
}
|
|
|
|
|
2020-06-24 20:48:04 +08:00
|
|
|
let mut words_attributes_docids = HashMap::new();
|
|
|
|
let number_attributes: u32 = 6;
|
|
|
|
|
|
|
|
for i in 0..number_attributes {
|
|
|
|
let mut intersect_docids: Option<RoaringBitmap> = None;
|
|
|
|
for derived_words in &words {
|
|
|
|
let mut union_docids = RoaringBitmap::new();
|
|
|
|
for (word, _) in derived_words {
|
|
|
|
// generate the key with the attribute number.
|
|
|
|
let mut key = word.to_vec();
|
|
|
|
key.extend_from_slice(&i.to_be_bytes());
|
|
|
|
|
|
|
|
if let Some(right) = self.word_attribute_docids.get(rtxn, &key)? {
|
|
|
|
union_docids.union_with(&right);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
match &mut intersect_docids {
|
|
|
|
Some(left) => left.intersect_with(&union_docids),
|
|
|
|
None => intersect_docids = Some(union_docids),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if let Some(docids) = intersect_docids {
|
|
|
|
words_attributes_docids.insert(i, docids);
|
|
|
|
}
|
|
|
|
}
|
2020-06-11 03:35:01 +08:00
|
|
|
|
2020-06-24 20:48:04 +08:00
|
|
|
eprintln!("The documents you must find for each attribute: {:?}", words_attributes_docids);
|
|
|
|
|
|
|
|
eprintln!("Retrieving words positions took {:.02?}", before.elapsed());
|
2020-06-10 22:54:22 +08:00
|
|
|
|
2020-06-20 21:38:10 +08:00
|
|
|
// Returns the union of the same position for all the derived words.
|
|
|
|
let unions_word_pos = |word: usize, pos: u32| {
|
|
|
|
let mut union_docids = RoaringBitmap::new();
|
|
|
|
for (word, attrs) in &words[word] {
|
|
|
|
if attrs.contains(pos) {
|
|
|
|
let mut key = word.clone();
|
|
|
|
key.extend_from_slice(&pos.to_be_bytes());
|
2020-06-23 00:02:22 +08:00
|
|
|
if let Some(right) = self.word_position_docids.get(rtxn, &key).unwrap() {
|
2020-06-20 21:38:10 +08:00
|
|
|
union_docids.union_with(&right);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
union_docids
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut union_cache = HashMap::new();
|
2020-06-14 19:10:30 +08:00
|
|
|
let mut intersect_cache = HashMap::new();
|
2020-06-20 21:38:10 +08:00
|
|
|
// Returns `true` if there is documents in common between the two words and positions given.
|
2020-06-24 21:06:45 +08:00
|
|
|
let mut contains_documents = |(lword, lpos), (rword, rpos), union_cache: &mut HashMap<_, _>, words_attributes_docids: &HashMap<_, _>| {
|
2020-06-16 18:10:23 +08:00
|
|
|
let proximity = best_proximity::positions_proximity(lpos, rpos);
|
2020-06-20 21:38:10 +08:00
|
|
|
|
2020-06-20 19:19:03 +08:00
|
|
|
if proximity == 0 { return false }
|
2020-06-16 18:10:23 +08:00
|
|
|
|
2020-06-20 21:38:10 +08:00
|
|
|
// We retrieve or compute the intersection between the two given words and positions.
|
2020-06-14 19:10:30 +08:00
|
|
|
*intersect_cache.entry(((lword, lpos), (rword, rpos))).or_insert_with(|| {
|
2020-06-20 21:38:10 +08:00
|
|
|
// We retrieve or compute the unions for the two words and positions.
|
|
|
|
union_cache.entry((lword, lpos)).or_insert_with(|| unions_word_pos(lword, lpos));
|
|
|
|
union_cache.entry((rword, rpos)).or_insert_with(|| unions_word_pos(rword, rpos));
|
2020-06-13 17:16:02 +08:00
|
|
|
|
2020-06-20 21:38:10 +08:00
|
|
|
// TODO is there a way to avoid this double gets?
|
|
|
|
let lunion_docids = union_cache.get(&(lword, lpos)).unwrap();
|
|
|
|
let runion_docids = union_cache.get(&(rword, rpos)).unwrap();
|
2020-06-16 18:10:23 +08:00
|
|
|
|
2020-06-24 21:06:45 +08:00
|
|
|
let lattr = lpos / 1000;
|
|
|
|
let rattr = rpos / 1000;
|
|
|
|
if lattr == rattr {
|
|
|
|
if let Some(docids) = words_attributes_docids.get(&lattr) {
|
|
|
|
if lunion_docids.is_disjoint(&docids) { return false }
|
|
|
|
if runion_docids.is_disjoint(&docids) { return false }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-20 21:38:10 +08:00
|
|
|
!lunion_docids.is_disjoint(&runion_docids)
|
2020-06-14 19:10:30 +08:00
|
|
|
})
|
2020-06-13 17:16:02 +08:00
|
|
|
};
|
|
|
|
|
2020-06-24 20:48:04 +08:00
|
|
|
let mut documents = Vec::new();
|
2020-06-21 18:24:51 +08:00
|
|
|
let mut iter = BestProximity::new(positions);
|
2020-06-24 21:06:45 +08:00
|
|
|
while let Some((proximity, mut positions)) = iter.next(|l, r| contains_documents(l, r, &mut union_cache, &words_attributes_docids)) {
|
2020-06-11 17:55:03 +08:00
|
|
|
positions.sort_unstable();
|
|
|
|
|
2020-06-11 03:35:01 +08:00
|
|
|
let same_prox_before = Instant::now();
|
2020-06-10 22:54:22 +08:00
|
|
|
let mut same_proximity_union = RoaringBitmap::default();
|
|
|
|
|
|
|
|
for positions in positions {
|
2020-06-11 03:35:01 +08:00
|
|
|
let before = Instant::now();
|
|
|
|
|
2020-06-10 22:54:22 +08:00
|
|
|
let mut intersect_docids: Option<RoaringBitmap> = None;
|
2020-06-21 18:24:51 +08:00
|
|
|
for (word, pos) in positions.iter().enumerate() {
|
2020-06-11 03:35:01 +08:00
|
|
|
let before = Instant::now();
|
2020-06-21 18:24:51 +08:00
|
|
|
let union_docids = union_cache.entry((word, *pos)).or_insert_with(|| unions_word_pos(word, *pos));
|
2020-06-05 22:32:14 +08:00
|
|
|
|
2020-06-11 03:35:01 +08:00
|
|
|
let before_intersect = Instant::now();
|
2020-06-10 22:54:22 +08:00
|
|
|
match &mut intersect_docids {
|
|
|
|
Some(left) => left.intersect_with(&union_docids),
|
2020-06-21 18:24:51 +08:00
|
|
|
None => intersect_docids = Some(union_docids.clone()),
|
2020-06-01 00:20:49 +08:00
|
|
|
}
|
2020-06-11 03:35:01 +08:00
|
|
|
|
2020-06-21 18:24:51 +08:00
|
|
|
eprintln!("retrieving words took {:.02?} and took {:.02?} to intersect",
|
|
|
|
before.elapsed(), before_intersect.elapsed());
|
2020-05-31 23:48:13 +08:00
|
|
|
}
|
2020-06-10 22:54:22 +08:00
|
|
|
|
2020-06-11 03:35:01 +08:00
|
|
|
eprintln!("for proximity {:?} {:?} we took {:.02?} to find {} documents",
|
|
|
|
proximity, positions, before.elapsed(),
|
|
|
|
intersect_docids.as_ref().map_or(0, |rb| rb.len()));
|
|
|
|
|
2020-06-10 22:54:22 +08:00
|
|
|
if let Some(intersect_docids) = intersect_docids {
|
|
|
|
same_proximity_union.union_with(&intersect_docids);
|
|
|
|
}
|
2020-06-05 22:32:14 +08:00
|
|
|
|
2020-06-11 17:55:03 +08:00
|
|
|
// We found enough documents we can stop here
|
|
|
|
if documents.iter().map(RoaringBitmap::len).sum::<u64>() + same_proximity_union.len() >= 20 {
|
|
|
|
eprintln!("proximity {} took a total of {:.02?}", proximity, same_prox_before.elapsed());
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2020-06-11 03:35:01 +08:00
|
|
|
|
2020-06-24 21:00:26 +08:00
|
|
|
// We achieve to find valid documents ids so we remove them from the candidate list.
|
|
|
|
for (_, docids) in &mut words_attributes_docids {
|
|
|
|
docids.difference_with(&same_proximity_union);
|
|
|
|
}
|
|
|
|
|
2020-06-10 22:54:22 +08:00
|
|
|
documents.push(same_proximity_union);
|
2020-06-06 02:12:52 +08:00
|
|
|
|
2020-06-11 17:55:03 +08:00
|
|
|
// We remove the double occurences of documents.
|
|
|
|
for i in 0..documents.len() {
|
|
|
|
if let Some((docs, others)) = documents[..=i].split_last_mut() {
|
|
|
|
others.iter().for_each(|other| docs.difference_with(other));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
documents.retain(|rb| !rb.is_empty());
|
|
|
|
|
|
|
|
eprintln!("documents: {:?}", documents);
|
|
|
|
eprintln!("proximity {} took a total of {:.02?}", proximity, same_prox_before.elapsed());
|
|
|
|
|
|
|
|
// We found enough documents we can stop here.
|
2020-06-10 22:54:22 +08:00
|
|
|
if documents.iter().map(RoaringBitmap::len).sum::<u64>() >= 20 {
|
2020-06-11 17:55:03 +08:00
|
|
|
break;
|
2020-06-05 01:13:28 +08:00
|
|
|
}
|
2020-05-31 23:48:13 +08:00
|
|
|
}
|
|
|
|
|
2020-06-10 22:54:22 +08:00
|
|
|
eprintln!("{} candidates", documents.iter().map(RoaringBitmap::len).sum::<u64>());
|
|
|
|
Ok(documents.iter().flatten().take(20).collect())
|
2020-05-31 23:48:13 +08:00
|
|
|
}
|
|
|
|
}
|