use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashMap};
use std::sync::Arc;
use super::corpus::{DocField, FieldStats};
use super::distance::bounded_distance;
use super::query::{Clause, Occur, Target};
use super::wildcard::Pattern;
const K1: f64 = 1.2;
const B: f64 = 0.75;
const MAX_FUZZY_EXPANSIONS: usize = 50;
struct Alternative {
term: String,
weight: f64,
}
enum FieldMatch {
Weighted(Vec<Alternative>),
Constant(Pattern),
}
pub(super) struct ResolvedClause<'a> {
pub(super) occur: Occur,
boost: f64,
by_field: HashMap<&'a str, FieldMatch>,
}
fn fuzzy_weight(edits: u8, query_chars: usize, candidate_chars: usize) -> Option<f64> {
let shorter = query_chars.min(candidate_chars);
(usize::from(edits) < shorter).then(|| 1.0 - f64::from(edits) / shorter as f64)
}
type FuzzyKey<'a> = (u8, Reverse<usize>, &'a str);
fn expand_fuzzy(term: &str, max_edits: u8, stat: &FieldStats) -> Vec<Alternative> {
let term_chars: Vec<char> = term.chars().collect();
let query_chars = term_chars.len();
let mut best: BinaryHeap<FuzzyKey<'_>> = BinaryHeap::new();
for (candidate, df) in &stat.df {
let Some(edits) = bounded_distance(&term_chars, candidate, max_edits) else {
continue;
};
if fuzzy_weight(edits, query_chars, candidate.chars().count()).is_none() {
continue;
}
best.push((edits, Reverse(*df), candidate.as_str()));
if best.len() > MAX_FUZZY_EXPANSIONS {
best.pop();
}
}
best.into_sorted_vec()
.into_iter()
.map(|(edits, _, term)| Alternative {
term: term.to_string(),
weight: fuzzy_weight(edits, query_chars, term.chars().count())
.expect("a kept candidate passed the match rule when it was pushed"),
})
.collect()
}
pub(super) fn resolve_clause<'a>(
clause: &Clause,
stats: &'a HashMap<Arc<str>, FieldStats>,
) -> ResolvedClause<'a> {
let by_field = stats
.iter()
.filter(|(field, _)| {
clause
.property
.as_deref()
.is_none_or(|wanted| wanted == &***field)
})
.map(|(field, stat)| {
let matched = match &clause.target {
Target::Term(term) => FieldMatch::Weighted(vec![Alternative {
term: term.clone(),
weight: 1.0,
}]),
Target::Fuzzy { term, edits } => {
FieldMatch::Weighted(expand_fuzzy(term, *edits, stat))
}
Target::Wildcard(pattern) => FieldMatch::Constant(pattern.clone()),
};
(&**field, matched)
})
.collect();
ResolvedClause {
occur: clause.occur,
boost: clause.boost,
by_field,
}
}
pub(super) fn clause_score(
clause: &ResolvedClause<'_>,
doc: &[DocField],
stats: &HashMap<Arc<str>, FieldStats>,
) -> Option<f64> {
let fields = doc.iter().filter_map(|field| {
let field_match = clause.by_field.get(&*field.property)?;
field_score(field_match, field, stats)
});
sum_matches(fields).map(|score| score * clause.boost)
}
fn sum_matches(scores: impl Iterator<Item = f64>) -> Option<f64> {
scores.fold(None, |sum, score| Some(sum.unwrap_or(0.0) + score))
}
fn field_score(
field_match: &FieldMatch,
field: &DocField,
stats: &HashMap<Arc<str>, FieldStats>,
) -> Option<f64> {
let alternatives = match field_match {
FieldMatch::Weighted(alternatives) => alternatives,
FieldMatch::Constant(pattern) => {
return field
.tokens
.iter()
.any(|token| pattern.matches(token))
.then_some(1.0);
}
};
let stat = stats
.get(&*field.property)
.expect("statistics exist for every indexed property");
let n = stat.docs as f64;
let dl = field.tokens.len() as f64;
let avgdl = stat.total_len as f64 / n;
let scores = alternatives.iter().filter_map(|alternative| {
let tf = field
.tokens
.iter()
.filter(|token| **token == alternative.term)
.count();
if tf == 0 {
return None;
}
let df = stat
.df
.get(&alternative.term)
.copied()
.expect("a carried token is in the field's document frequency table");
let idf = (1.0 + (n - df as f64 + 0.5) / (df as f64 + 0.5)).ln();
let tf = tf as f64;
Some(alternative.weight * idf * tf / (tf + K1 * (1.0 - B + B * dl / avgdl)))
});
sum_matches(scores)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_wildcard_group_scores_a_constant_per_field() {
let stat = stat_of(&[("lampa", 1), ("lampb", 1), ("other", 1)]);
let stats = HashMap::from([(Arc::<str>::from("name"), stat)]);
let clause = ResolvedClause {
occur: Occur::Should,
boost: 2.0,
by_field: HashMap::from([("name", FieldMatch::Constant(Pattern::must_parse("lamp?")))]),
};
let field = |tokens: &[&str]| DocField {
property: Arc::from("name"),
tokens: tokens.iter().map(|t| t.to_string()).collect(),
};
let doc = [field(&["lampa", "lampa", "lampb", "x", "y", "z"])];
assert_eq!(clause_score(&clause, &doc, &stats), Some(2.0));
assert_eq!(clause_score(&clause, &[field(&["other"])], &stats), None);
}
fn stat_of(terms: &[(&str, usize)]) -> FieldStats {
FieldStats {
docs: 10,
total_len: 100,
df: terms.iter().map(|(t, df)| (t.to_string(), *df)).collect(),
}
}
fn terms(alternatives: &[Alternative]) -> Vec<&str> {
alternatives.iter().map(|a| a.term.as_str()).collect()
}
#[test]
fn expansion_orders_closest_then_frequent_then_lexicographic() {
let stat = stat_of(&[
("kollegger", 1),
("kolleger", 3),
("kollegers", 5),
("kolleges", 5),
("unrelated", 9),
]);
let expanded = expand_fuzzy("kolleger", 1, &stat);
assert_eq!(
terms(&expanded),
["kolleger", "kollegers", "kolleges", "kollegger"]
);
assert_eq!(expanded[0].weight, 1.0);
assert!(expanded[1].weight < 1.0 && expanded[1].weight > 0.0);
assert_eq!(terms(&expand_fuzzy("kolleger", 0, &stat)), ["kolleger"]);
}
#[test]
fn expansion_is_capped_and_deterministic() {
let owned: Vec<(String, usize)> = (0..80).map(|i| (format!("lam{i:02}"), 1)).collect();
let vocabulary: Vec<(&str, usize)> =
owned.iter().map(|(t, df)| (t.as_str(), *df)).collect();
let first = expand_fuzzy("lamp", 2, &stat_of(&vocabulary));
assert_eq!(first.len(), MAX_FUZZY_EXPANSIONS);
let mut reversed = vocabulary.clone();
reversed.reverse();
let second = expand_fuzzy("lamp", 2, &stat_of(&reversed));
assert_eq!(terms(&first), terms(&second));
let mut sorted = terms(&first);
sorted.sort();
assert_eq!(terms(&first), sorted, "ties break lexicographically");
}
#[test]
fn weight_falls_with_distance_and_never_reaches_zero_in_a_match() {
assert_eq!(fuzzy_weight(0, 8, 8), Some(1.0));
let (one_edit, two_edits) = (
fuzzy_weight(1, 8, 9).expect("one edit on a nine-character candidate matches"),
fuzzy_weight(2, 8, 9).expect("two edits on a nine-character candidate match"),
);
assert!(one_edit > two_edits);
assert_eq!(fuzzy_weight(2, 2, 9), None);
assert_eq!(fuzzy_weight(0, 0, 3), None);
let stat = stat_of(&[("ab", 1)]);
assert!(expand_fuzzy("xy", 2, &stat).is_empty());
}
}