2020-11-20 10:54:41 +01:00
|
|
|
use std::borrow::Cow;
|
2021-04-13 19:10:58 +02:00
|
|
|
use std::collections::hash_map::{Entry, HashMap};
|
2020-11-20 10:54:41 +01:00
|
|
|
use std::fmt;
|
2021-04-14 12:18:13 +02:00
|
|
|
use std::mem::take;
|
2021-06-14 16:46:19 +02:00
|
|
|
use std::result::Result as StdResult;
|
2021-03-05 11:02:24 +01:00
|
|
|
use std::str::Utf8Error;
|
2020-12-02 11:36:38 +01:00
|
|
|
use std::time::Instant;
|
2020-11-20 10:54:41 +01:00
|
|
|
|
2022-06-02 15:47:28 +02:00
|
|
|
use charabia::TokenizerBuilder;
|
2021-06-16 18:33:33 +02:00
|
|
|
use distinct::{Distinct, DocIter, FacetDistinct, NoopDistinct};
|
2022-01-20 18:35:11 +01:00
|
|
|
use fst::automaton::Str;
|
|
|
|
use fst::{Automaton, IntoStreamer, Streamer};
|
2021-04-13 19:10:58 +02:00
|
|
|
use levenshtein_automata::{LevenshteinAutomatonBuilder as LevBuilder, DFA};
|
2020-11-20 10:54:41 +01:00
|
|
|
use log::debug;
|
|
|
|
use once_cell::sync::Lazy;
|
|
|
|
use roaring::bitmap::RoaringBitmap;
|
|
|
|
|
2022-06-08 17:28:23 +02:00
|
|
|
pub use self::facet::{FacetDistribution, FacetNumberIter, Filter, DEFAULT_VALUES_PER_FACET};
|
2022-03-15 17:28:57 +01:00
|
|
|
use self::fst_utils::{Complement, Intersection, StartsWith, Union};
|
2022-04-12 16:31:58 +02:00
|
|
|
pub use self::matches::{
|
|
|
|
FormatOptions, MatchBounds, Matcher, MatcherBuilder, MatchingWord, MatchingWords,
|
|
|
|
};
|
2021-04-13 19:10:58 +02:00
|
|
|
use self::query_tree::QueryTreeBuilder;
|
2021-08-23 11:37:18 +02:00
|
|
|
use crate::error::UserError;
|
2021-06-16 18:33:33 +02:00
|
|
|
use crate::search::criteria::r#final::{Final, FinalResult};
|
2021-09-22 16:29:11 +02:00
|
|
|
use crate::{AscDesc, Criterion, DocumentId, Index, Member, Result};
|
2021-06-15 11:51:32 +02:00
|
|
|
|
2020-11-20 10:54:41 +01: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));
|
|
|
|
|
2021-04-07 12:38:48 +02:00
|
|
|
mod criteria;
|
|
|
|
mod distinct;
|
2020-11-20 10:54:41 +01:00
|
|
|
mod facet;
|
2022-03-15 17:28:57 +01:00
|
|
|
mod fst_utils;
|
2022-03-22 15:22:14 +01:00
|
|
|
mod matches;
|
2021-06-16 18:33:33 +02:00
|
|
|
mod query_tree;
|
2020-11-20 10:54:41 +01:00
|
|
|
|
|
|
|
pub struct Search<'a> {
|
|
|
|
query: Option<String>,
|
2021-10-22 01:59:38 +02:00
|
|
|
// this should be linked to the String in the query
|
2021-10-22 14:33:18 +02:00
|
|
|
filter: Option<Filter<'a>>,
|
2020-11-20 10:54:41 +01:00
|
|
|
offset: usize,
|
|
|
|
limit: usize,
|
2021-08-23 11:37:18 +02:00
|
|
|
sort_criteria: Option<Vec<AscDesc>>,
|
2022-08-18 17:36:08 +02:00
|
|
|
optional_words: TermsMatchingStrategy,
|
2021-03-10 11:16:30 +01:00
|
|
|
authorize_typos: bool,
|
2021-04-13 19:10:58 +02:00
|
|
|
words_limit: usize,
|
2020-11-20 10:54:41 +01:00
|
|
|
rtxn: &'a heed::RoTxn<'a>,
|
|
|
|
index: &'a Index,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Search<'a> {
|
|
|
|
pub fn new(rtxn: &'a heed::RoTxn, index: &'a Index) -> Search<'a> {
|
2021-03-10 11:16:30 +01:00
|
|
|
Search {
|
|
|
|
query: None,
|
2021-06-01 15:25:17 +02:00
|
|
|
filter: None,
|
2021-03-10 11:16:30 +01:00
|
|
|
offset: 0,
|
|
|
|
limit: 20,
|
2021-08-23 11:37:18 +02:00
|
|
|
sort_criteria: None,
|
2022-08-18 17:36:08 +02:00
|
|
|
optional_words: TermsMatchingStrategy::default(),
|
2021-03-10 11:16:30 +01:00
|
|
|
authorize_typos: true,
|
2021-04-13 19:10:58 +02:00
|
|
|
words_limit: 10,
|
2021-03-10 11:16:30 +01:00
|
|
|
rtxn,
|
|
|
|
index,
|
|
|
|
}
|
2020-11-20 10:54:41 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn query(&mut self, query: impl Into<String>) -> &mut Search<'a> {
|
|
|
|
self.query = Some(query.into());
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn offset(&mut self, offset: usize) -> &mut Search<'a> {
|
|
|
|
self.offset = offset;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn limit(&mut self, limit: usize) -> &mut Search<'a> {
|
|
|
|
self.limit = limit;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-08-23 11:37:18 +02:00
|
|
|
pub fn sort_criteria(&mut self, criteria: Vec<AscDesc>) -> &mut Search<'a> {
|
|
|
|
self.sort_criteria = Some(criteria);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2022-08-18 17:36:08 +02:00
|
|
|
pub fn optional_words(&mut self, value: TermsMatchingStrategy) -> &mut Search<'a> {
|
2021-03-10 11:16:30 +01:00
|
|
|
self.optional_words = value;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn authorize_typos(&mut self, value: bool) -> &mut Search<'a> {
|
|
|
|
self.authorize_typos = value;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-04-13 19:10:58 +02:00
|
|
|
pub fn words_limit(&mut self, value: usize) -> &mut Search<'a> {
|
|
|
|
self.words_limit = value;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2021-10-22 14:33:18 +02:00
|
|
|
pub fn filter(&mut self, condition: Filter<'a>) -> &mut Search<'a> {
|
2021-06-01 15:25:17 +02:00
|
|
|
self.filter = Some(condition);
|
2020-11-20 10:54:41 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2022-03-31 09:54:49 +02:00
|
|
|
fn is_typo_authorized(&self) -> Result<bool> {
|
|
|
|
let index_authorizes_typos = self.index.authorize_typos(self.rtxn)?;
|
|
|
|
// only authorize typos if both the index and the query allow it.
|
|
|
|
Ok(self.authorize_typos && index_authorizes_typos)
|
|
|
|
}
|
|
|
|
|
2021-06-14 16:46:19 +02:00
|
|
|
pub fn execute(&self) -> Result<SearchResult> {
|
2021-02-17 10:29:28 +01:00
|
|
|
// We create the query tree by spliting the query into tokens.
|
|
|
|
let before = Instant::now();
|
2022-04-04 18:56:59 +02:00
|
|
|
let (query_tree, primitive_query, matching_words) = match self.query.as_ref() {
|
2021-02-17 10:29:28 +01:00
|
|
|
Some(query) => {
|
2022-05-24 09:43:17 +02:00
|
|
|
let mut builder = QueryTreeBuilder::new(self.rtxn, self.index)?;
|
2021-03-10 11:16:30 +01:00
|
|
|
builder.optional_words(self.optional_words);
|
2022-03-16 10:03:18 +01:00
|
|
|
|
2022-03-31 09:54:49 +02:00
|
|
|
builder.authorize_typos(self.is_typo_authorized()?);
|
2022-03-16 10:03:18 +01:00
|
|
|
|
2021-04-13 19:10:58 +02:00
|
|
|
builder.words_limit(self.words_limit);
|
2021-04-08 21:21:20 +02:00
|
|
|
// We make sure that the analyzer is aware of the stop words
|
|
|
|
// this ensures that the query builder is able to properly remove them.
|
2022-06-02 15:47:28 +02:00
|
|
|
let mut tokbuilder = TokenizerBuilder::new();
|
2021-04-08 21:21:20 +02:00
|
|
|
let stop_words = self.index.stop_words(self.rtxn)?;
|
|
|
|
if let Some(ref stop_words) = stop_words {
|
2022-06-02 15:47:28 +02:00
|
|
|
tokbuilder.stop_words(stop_words);
|
2021-04-08 21:21:20 +02:00
|
|
|
}
|
2022-06-02 15:47:28 +02:00
|
|
|
|
|
|
|
let tokenizer = tokbuilder.build();
|
|
|
|
let tokens = tokenizer.tokenize(query);
|
2022-04-04 18:56:59 +02:00
|
|
|
builder
|
|
|
|
.build(tokens)?
|
|
|
|
.map_or((None, None, None), |(qt, pq, mw)| (Some(qt), Some(pq), Some(mw)))
|
2021-06-16 18:33:33 +02:00
|
|
|
}
|
2022-04-04 18:56:59 +02:00
|
|
|
None => (None, None, None),
|
2020-11-20 10:54:41 +01:00
|
|
|
};
|
|
|
|
|
2021-02-17 10:29:28 +01:00
|
|
|
debug!("query tree: {:?} took {:.02?}", query_tree, before.elapsed());
|
|
|
|
|
2020-11-20 10:54:41 +01:00
|
|
|
// We create the original candidates with the facet conditions results.
|
2020-12-02 11:36:38 +01:00
|
|
|
let before = Instant::now();
|
2021-06-01 15:25:17 +02:00
|
|
|
let filtered_candidates = match &self.filter {
|
2020-11-21 13:09:49 +01:00
|
|
|
Some(condition) => Some(condition.evaluate(self.rtxn, self.index)?),
|
2020-11-20 10:54:41 +01:00
|
|
|
None => None,
|
|
|
|
};
|
|
|
|
|
2021-06-01 15:25:17 +02:00
|
|
|
debug!("facet candidates: {:?} took {:.02?}", filtered_candidates, before.elapsed());
|
2020-12-02 11:36:38 +01:00
|
|
|
|
2021-08-23 11:37:18 +02:00
|
|
|
// We check that we are allowed to use the sort criteria, we check
|
|
|
|
// that they are declared in the sortable fields.
|
|
|
|
if let Some(sort_criteria) = &self.sort_criteria {
|
2021-08-31 20:29:58 +02:00
|
|
|
let sortable_fields = self.index.sortable_fields(self.rtxn)?;
|
2021-08-23 11:37:18 +02:00
|
|
|
for asc_desc in sort_criteria {
|
2021-09-22 16:29:11 +02:00
|
|
|
match asc_desc.member() {
|
2022-03-23 17:28:41 +01:00
|
|
|
Member::Field(ref field) if !crate::is_faceted(field, &sortable_fields) => {
|
2021-08-30 18:22:52 +02:00
|
|
|
return Err(UserError::InvalidSortableAttribute {
|
|
|
|
field: field.to_string(),
|
2021-10-28 11:18:32 +02:00
|
|
|
valid_fields: sortable_fields.into_iter().collect(),
|
2021-09-22 16:29:11 +02:00
|
|
|
})?
|
2021-08-23 11:37:18 +02:00
|
|
|
}
|
2021-09-22 16:29:11 +02:00
|
|
|
Member::Geo(_) if !sortable_fields.contains("_geo") => {
|
|
|
|
return Err(UserError::InvalidSortableAttribute {
|
|
|
|
field: "_geo".to_string(),
|
2021-10-28 11:18:32 +02:00
|
|
|
valid_fields: sortable_fields.into_iter().collect(),
|
2021-09-22 16:29:11 +02:00
|
|
|
})?
|
|
|
|
}
|
|
|
|
_ => (),
|
2021-08-23 11:37:18 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-07 10:52:19 +02:00
|
|
|
// We check that the sort ranking rule exists and throw an
|
|
|
|
// error if we try to use it and that it doesn't.
|
|
|
|
let sort_ranking_rule_missing = !self.index.criteria(self.rtxn)?.contains(&Criterion::Sort);
|
|
|
|
let empty_sort_criteria = self.sort_criteria.as_ref().map_or(true, |s| s.is_empty());
|
|
|
|
if sort_ranking_rule_missing && !empty_sort_criteria {
|
|
|
|
return Err(UserError::SortRankingRuleMissing.into());
|
|
|
|
}
|
|
|
|
|
2021-03-02 11:58:32 +01:00
|
|
|
let criteria_builder = criteria::CriteriaBuilder::new(self.rtxn, self.index)?;
|
2021-08-23 11:37:18 +02:00
|
|
|
let criteria = criteria_builder.build(
|
|
|
|
query_tree,
|
|
|
|
primitive_query,
|
|
|
|
filtered_candidates,
|
|
|
|
self.sort_criteria.clone(),
|
|
|
|
)?;
|
2021-04-07 12:38:48 +02:00
|
|
|
|
2021-06-01 16:29:14 +02:00
|
|
|
match self.index.distinct_field(self.rtxn)? {
|
2022-04-04 18:56:59 +02:00
|
|
|
None => self.perform_sort(NoopDistinct, matching_words.unwrap_or_default(), criteria),
|
2021-04-07 12:38:48 +02:00
|
|
|
Some(name) => {
|
|
|
|
let field_ids_map = self.index.fields_ids_map(self.rtxn)?;
|
2021-07-22 17:11:17 +02:00
|
|
|
match field_ids_map.id(name) {
|
|
|
|
Some(fid) => {
|
|
|
|
let distinct = FacetDistinct::new(fid, self.index, self.rtxn);
|
2022-04-04 18:56:59 +02:00
|
|
|
self.perform_sort(distinct, matching_words.unwrap_or_default(), criteria)
|
2021-07-22 17:11:17 +02:00
|
|
|
}
|
|
|
|
None => Ok(SearchResult::default()),
|
|
|
|
}
|
2021-04-07 12:38:48 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-01 14:43:48 +02:00
|
|
|
fn perform_sort<D: Distinct>(
|
2021-04-07 12:38:48 +02:00
|
|
|
&self,
|
2021-06-01 14:43:48 +02:00
|
|
|
mut distinct: D,
|
2021-04-07 12:38:48 +02:00
|
|
|
matching_words: MatchingWords,
|
2021-03-23 15:25:46 +01:00
|
|
|
mut criteria: Final,
|
2021-06-16 18:33:33 +02:00
|
|
|
) -> Result<SearchResult> {
|
2021-02-17 10:29:28 +01:00
|
|
|
let mut offset = self.offset;
|
2021-02-17 17:50:46 +01:00
|
|
|
let mut initial_candidates = RoaringBitmap::new();
|
2022-06-13 17:59:34 +02:00
|
|
|
let mut excluded_candidates = self.index.soft_deleted_documents_ids(self.rtxn)?;
|
2021-06-22 14:52:13 +02:00
|
|
|
let mut documents_ids = Vec::new();
|
2021-04-07 12:38:48 +02:00
|
|
|
|
2021-06-16 18:33:33 +02:00
|
|
|
while let Some(FinalResult { candidates, bucket_candidates, .. }) =
|
|
|
|
criteria.next(&excluded_candidates)?
|
|
|
|
{
|
2021-02-24 15:37:37 +01:00
|
|
|
debug!("Number of candidates found {}", candidates.len());
|
|
|
|
|
2021-04-28 18:01:23 +02:00
|
|
|
let excluded = take(&mut excluded_candidates);
|
2021-04-07 12:38:48 +02:00
|
|
|
let mut candidates = distinct.distinct(candidates, excluded);
|
2021-02-17 17:50:46 +01:00
|
|
|
|
2021-06-30 14:12:56 +02:00
|
|
|
initial_candidates |= bucket_candidates;
|
2020-11-20 10:54:41 +01:00
|
|
|
|
2021-02-17 10:29:28 +01:00
|
|
|
if offset != 0 {
|
2021-04-07 12:38:48 +02:00
|
|
|
let discarded = candidates.by_ref().take(offset).count();
|
|
|
|
offset = offset.saturating_sub(discarded);
|
2020-11-20 10:54:41 +01:00
|
|
|
}
|
|
|
|
|
2021-04-07 12:38:48 +02:00
|
|
|
for candidate in candidates.by_ref().take(self.limit - documents_ids.len()) {
|
|
|
|
documents_ids.push(candidate?);
|
2021-02-17 10:29:28 +01:00
|
|
|
}
|
2022-06-22 11:37:04 +02:00
|
|
|
|
|
|
|
excluded_candidates |= candidates.into_excluded();
|
|
|
|
|
2021-06-16 18:33:33 +02:00
|
|
|
if documents_ids.len() == self.limit {
|
|
|
|
break;
|
|
|
|
}
|
2021-02-17 10:29:28 +01:00
|
|
|
}
|
|
|
|
|
2022-04-09 14:30:00 +02:00
|
|
|
Ok(SearchResult {
|
|
|
|
matching_words,
|
|
|
|
candidates: initial_candidates - excluded_candidates,
|
|
|
|
documents_ids,
|
|
|
|
})
|
2020-11-20 10:54:41 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Debug for Search<'_> {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
2021-03-10 11:16:30 +01:00
|
|
|
let Search {
|
|
|
|
query,
|
2021-06-01 15:25:17 +02:00
|
|
|
filter,
|
2021-03-10 11:16:30 +01:00
|
|
|
offset,
|
|
|
|
limit,
|
2021-08-23 11:37:18 +02:00
|
|
|
sort_criteria,
|
2021-03-10 11:16:30 +01:00
|
|
|
optional_words,
|
|
|
|
authorize_typos,
|
2021-04-13 19:10:58 +02:00
|
|
|
words_limit,
|
2021-03-10 11:16:30 +01:00
|
|
|
rtxn: _,
|
|
|
|
index: _,
|
|
|
|
} = self;
|
2020-11-20 10:54:41 +01:00
|
|
|
f.debug_struct("Search")
|
2020-11-22 15:40:11 +01:00
|
|
|
.field("query", query)
|
2021-06-01 15:25:17 +02:00
|
|
|
.field("filter", filter)
|
2020-11-22 15:40:11 +01:00
|
|
|
.field("offset", offset)
|
|
|
|
.field("limit", limit)
|
2021-08-23 11:37:18 +02:00
|
|
|
.field("sort_criteria", sort_criteria)
|
2021-03-10 11:16:30 +01:00
|
|
|
.field("optional_words", optional_words)
|
|
|
|
.field("authorize_typos", authorize_typos)
|
2021-04-13 19:10:58 +02:00
|
|
|
.field("words_limit", words_limit)
|
2020-11-20 10:54:41 +01:00
|
|
|
.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Default)]
|
|
|
|
pub struct SearchResult {
|
2021-02-24 17:44:35 +01:00
|
|
|
pub matching_words: MatchingWords,
|
2020-12-28 19:08:53 +01:00
|
|
|
pub candidates: RoaringBitmap,
|
2020-11-20 10:54:41 +01:00
|
|
|
// TODO those documents ids should be associated with their criteria scores.
|
|
|
|
pub documents_ids: Vec<DocumentId>,
|
|
|
|
}
|
2021-03-03 12:03:31 +01:00
|
|
|
|
2022-08-18 17:36:08 +02:00
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
|
|
pub enum TermsMatchingStrategy {
|
|
|
|
// remove last word first
|
|
|
|
Last,
|
|
|
|
// remove first word first
|
|
|
|
First,
|
|
|
|
// remove more frequent word first
|
|
|
|
Frequency,
|
|
|
|
// remove smallest word first
|
|
|
|
Size,
|
|
|
|
// only one of the word is mandatory
|
|
|
|
Any,
|
|
|
|
// all words are mandatory
|
|
|
|
All,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for TermsMatchingStrategy {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self::Last
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-05 11:02:24 +01:00
|
|
|
pub type WordDerivationsCache = HashMap<(String, bool, u8), Vec<(String, u8)>>;
|
|
|
|
|
|
|
|
pub fn word_derivations<'c>(
|
2021-02-24 17:44:35 +01:00
|
|
|
word: &str,
|
|
|
|
is_prefix: bool,
|
|
|
|
max_typo: u8,
|
|
|
|
fst: &fst::Set<Cow<[u8]>>,
|
2021-03-05 11:02:24 +01:00
|
|
|
cache: &'c mut WordDerivationsCache,
|
2021-06-14 16:46:19 +02:00
|
|
|
) -> StdResult<&'c [(String, u8)], Utf8Error> {
|
2021-03-05 11:02:24 +01:00
|
|
|
match cache.entry((word.to_string(), is_prefix, max_typo)) {
|
|
|
|
Entry::Occupied(entry) => Ok(entry.into_mut()),
|
|
|
|
Entry::Vacant(entry) => {
|
|
|
|
let mut derived_words = Vec::new();
|
2022-01-20 23:23:07 +01:00
|
|
|
if max_typo == 0 {
|
|
|
|
if is_prefix {
|
|
|
|
let prefix = Str::new(word).starts_with();
|
|
|
|
let mut stream = fst.search(prefix).into_stream();
|
|
|
|
|
|
|
|
while let Some(word) = stream.next() {
|
|
|
|
let word = std::str::from_utf8(word)?;
|
|
|
|
derived_words.push((word.to_string(), 0));
|
|
|
|
}
|
2022-01-25 10:06:27 +01:00
|
|
|
} else if fst.contains(word) {
|
|
|
|
derived_words.push((word.to_string(), 0));
|
2022-01-20 18:35:11 +01:00
|
|
|
}
|
|
|
|
} else {
|
2022-01-20 23:23:07 +01:00
|
|
|
if max_typo == 1 {
|
|
|
|
let dfa = build_dfa(word, 1, is_prefix);
|
2022-03-15 17:28:57 +01:00
|
|
|
let starts = StartsWith(Str::new(get_first(word)));
|
|
|
|
let mut stream =
|
|
|
|
fst.search_with_state(Intersection(starts, &dfa)).into_stream();
|
2022-01-20 23:23:07 +01:00
|
|
|
|
2022-02-02 18:45:11 +01:00
|
|
|
while let Some((word, state)) = stream.next() {
|
2022-01-20 23:23:07 +01:00
|
|
|
let word = std::str::from_utf8(word)?;
|
2022-02-02 18:45:11 +01:00
|
|
|
let d = dfa.distance(state.1);
|
|
|
|
derived_words.push((word.to_string(), d.to_u8()));
|
2022-01-20 23:23:07 +01:00
|
|
|
}
|
|
|
|
} else {
|
2022-03-15 17:28:57 +01:00
|
|
|
let starts = StartsWith(Str::new(get_first(word)));
|
|
|
|
let first = Intersection(build_dfa(word, 1, is_prefix), Complement(&starts));
|
2022-02-02 18:45:11 +01:00
|
|
|
let second_dfa = build_dfa(word, 2, is_prefix);
|
2022-03-15 17:28:57 +01:00
|
|
|
let second = Intersection(&second_dfa, &starts);
|
|
|
|
let automaton = Union(first, &second);
|
2022-02-02 18:45:11 +01:00
|
|
|
|
|
|
|
let mut stream = fst.search_with_state(automaton).into_stream();
|
|
|
|
|
|
|
|
while let Some((found_word, state)) = stream.next() {
|
|
|
|
let found_word = std::str::from_utf8(found_word)?;
|
|
|
|
// in the case the typo is on the first letter, we know the number of typo
|
|
|
|
// is two
|
|
|
|
if get_first(found_word) != get_first(word) {
|
2022-04-01 10:51:22 +02:00
|
|
|
derived_words.push((found_word.to_string(), 2));
|
2022-02-02 18:45:11 +01:00
|
|
|
} else {
|
|
|
|
// Else, we know that it is the second dfa that matched and compute the
|
|
|
|
// correct distance
|
|
|
|
let d = second_dfa.distance((state.1).0);
|
2022-04-01 10:51:22 +02:00
|
|
|
derived_words.push((found_word.to_string(), d.to_u8()));
|
2022-02-02 18:45:11 +01:00
|
|
|
}
|
2022-01-20 23:23:07 +01:00
|
|
|
}
|
|
|
|
}
|
2022-01-20 18:35:11 +01:00
|
|
|
}
|
2022-01-20 23:23:07 +01:00
|
|
|
Ok(entry.insert(derived_words))
|
2021-06-16 18:33:33 +02:00
|
|
|
}
|
2021-03-05 11:02:24 +01:00
|
|
|
}
|
2021-03-03 12:03:31 +01:00
|
|
|
}
|
2021-02-24 17:44:35 +01:00
|
|
|
|
2022-01-20 18:35:11 +01:00
|
|
|
fn get_first(s: &str) -> &str {
|
|
|
|
match s.chars().next() {
|
|
|
|
Some(c) => &s[..c.len_utf8()],
|
2022-01-25 10:06:27 +01:00
|
|
|
None => panic!("unexpected empty query"),
|
2022-01-20 18:35:11 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-24 17:44:35 +01:00
|
|
|
pub fn build_dfa(word: &str, typos: u8, is_prefix: bool) -> DFA {
|
|
|
|
let lev = match typos {
|
|
|
|
0 => &LEVDIST0,
|
|
|
|
1 => &LEVDIST1,
|
|
|
|
_ => &LEVDIST2,
|
|
|
|
};
|
|
|
|
|
|
|
|
if is_prefix {
|
|
|
|
lev.build_prefix_dfa(word)
|
|
|
|
} else {
|
|
|
|
lev.build_dfa(word)
|
|
|
|
}
|
|
|
|
}
|
2022-03-31 09:54:49 +02:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::*;
|
2022-03-31 14:06:23 +02:00
|
|
|
use crate::index::tests::TempIndex;
|
2022-03-31 09:54:49 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_is_authorized_typos() {
|
|
|
|
let index = TempIndex::new();
|
|
|
|
let mut txn = index.write_txn().unwrap();
|
|
|
|
|
|
|
|
let mut search = Search::new(&txn, &index);
|
|
|
|
|
|
|
|
// default is authorized
|
|
|
|
assert!(search.is_typo_authorized().unwrap());
|
|
|
|
|
|
|
|
search.authorize_typos(false);
|
|
|
|
assert!(!search.is_typo_authorized().unwrap());
|
|
|
|
|
|
|
|
index.put_authorize_typos(&mut txn, false).unwrap();
|
|
|
|
txn.commit().unwrap();
|
|
|
|
|
|
|
|
let txn = index.read_txn().unwrap();
|
|
|
|
let mut search = Search::new(&txn, &index);
|
|
|
|
|
|
|
|
assert!(!search.is_typo_authorized().unwrap());
|
|
|
|
|
|
|
|
search.authorize_typos(true);
|
|
|
|
assert!(!search.is_typo_authorized().unwrap());
|
|
|
|
}
|
2022-04-01 11:05:18 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_one_typos_tolerance() {
|
|
|
|
let fst = fst::Set::from_iter(["zealand"].iter()).unwrap().map_data(Cow::Owned).unwrap();
|
|
|
|
let mut cache = HashMap::new();
|
|
|
|
let found = word_derivations("zealend", false, 1, &fst, &mut cache).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(found, &[("zealand".to_string(), 1)]);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_one_typos_first_letter() {
|
|
|
|
let fst = fst::Set::from_iter(["zealand"].iter()).unwrap().map_data(Cow::Owned).unwrap();
|
|
|
|
let mut cache = HashMap::new();
|
|
|
|
let found = word_derivations("sealand", false, 1, &fst, &mut cache).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(found, &[]);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_two_typos_tolerance() {
|
|
|
|
let fst = fst::Set::from_iter(["zealand"].iter()).unwrap().map_data(Cow::Owned).unwrap();
|
|
|
|
let mut cache = HashMap::new();
|
|
|
|
let found = word_derivations("zealemd", false, 2, &fst, &mut cache).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(found, &[("zealand".to_string(), 2)]);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_two_typos_first_letter() {
|
|
|
|
let fst = fst::Set::from_iter(["zealand"].iter()).unwrap().map_data(Cow::Owned).unwrap();
|
|
|
|
let mut cache = HashMap::new();
|
|
|
|
let found = word_derivations("sealand", false, 2, &fst, &mut cache).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(found, &[("zealand".to_string(), 2)]);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_prefix() {
|
|
|
|
let fst = fst::Set::from_iter(["zealand"].iter()).unwrap().map_data(Cow::Owned).unwrap();
|
|
|
|
let mut cache = HashMap::new();
|
|
|
|
let found = word_derivations("ze", true, 0, &fst, &mut cache).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(found, &[("zealand".to_string(), 0)]);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_bad_prefix() {
|
|
|
|
let fst = fst::Set::from_iter(["zealand"].iter()).unwrap().map_data(Cow::Owned).unwrap();
|
|
|
|
let mut cache = HashMap::new();
|
|
|
|
let found = word_derivations("se", true, 0, &fst, &mut cache).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(found, &[]);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_prefix_with_typo() {
|
|
|
|
let fst = fst::Set::from_iter(["zealand"].iter()).unwrap().map_data(Cow::Owned).unwrap();
|
|
|
|
let mut cache = HashMap::new();
|
|
|
|
let found = word_derivations("zae", true, 1, &fst, &mut cache).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(found, &[("zealand".to_string(), 1)]);
|
|
|
|
}
|
2022-03-31 09:54:49 +02:00
|
|
|
}
|