use std::cmp::Ordering;
use std::collections::{BTreeSet, HashMap};
use unicode_normalization::UnicodeNormalization as _;
const K1: f64 = 1.2;
const B: f64 = 0.75;
const FIELD_COUNT: usize = 3;
const IDF_SMOOTHING: f64 = 0.5;
const EXACT_NUMBER_BONUS: f64 = 100.0;
const PREFIX_NUMBER_BONUS: f64 = 10.0;
const FIELD_WEIGHTS: [f64; FIELD_COUNT] = [1.0, 0.35, 0.5];
const STOP_WORDS: &[&str] = &[
"a", "an", "and", "the", "of", "to", "in", "for", "with", "on", "or", "by", "is",
];
pub const MAX_RESULTS: usize = 8;
pub fn fold(text: &str) -> String {
text.nfkd()
.filter(|c| !('\u{300}'..='\u{36f}').contains(c))
.flat_map(char::to_lowercase)
.collect()
}
pub fn tokenize(text: &str) -> Vec<String> {
fold(text)
.split(|c: char| !c.is_alphanumeric())
.filter(|token| !token.is_empty() && !STOP_WORDS.contains(token))
.map(str::to_string)
.collect()
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SearchDoc {
pub id: String,
pub number: Option<u64>,
pub title: String,
pub parent: String,
pub meta: String,
}
impl SearchDoc {
pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
Self {
id: id.into(),
title: title.into(),
..Self::default()
}
}
pub fn number(mut self, number: u64) -> Self {
self.number = Some(number);
self
}
pub fn parent(mut self, parent: impl Into<String>) -> Self {
self.parent = parent.into();
self
}
pub fn meta(mut self, meta: impl Into<String>) -> Self {
self.meta = meta.into();
self
}
fn fields(&self) -> [&str; 3] {
[&self.title, &self.parent, &self.meta]
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Hit {
pub index: usize,
pub score: f64,
}
struct Indexed {
terms: [HashMap<String, u32>; FIELD_COUNT],
lengths: [usize; FIELD_COUNT],
}
pub struct SearchIndex {
docs: Vec<SearchDoc>,
indexed: Vec<Indexed>,
average: [f64; FIELD_COUNT],
frequency: [HashMap<String, u32>; FIELD_COUNT],
vocabulary: BTreeSet<String>,
}
impl SearchIndex {
pub fn new(docs: Vec<SearchDoc>) -> Self {
let indexed: Vec<Indexed> = docs
.iter()
.map(|doc| {
let tokens = doc.fields().map(tokenize);
Indexed {
lengths: [tokens[0].len(), tokens[1].len(), tokens[2].len()],
terms: tokens.map(|tokens| {
let mut counts = HashMap::new();
for token in tokens {
*counts.entry(token).or_insert(0) += 1;
}
counts
}),
}
})
.collect();
let mut average = [1.0; FIELD_COUNT];
let mut frequency: [HashMap<String, u32>; FIELD_COUNT] = Default::default();
let mut vocabulary = BTreeSet::new();
for field in 0..FIELD_COUNT {
let total: usize = indexed.iter().map(|doc| doc.lengths[field]).sum();
let mean = total as f64 / indexed.len().max(1) as f64;
average[field] = if mean > 0.0 { mean } else { 1.0 };
for doc in &indexed {
for term in doc.terms[field].keys() {
*frequency[field].entry(term.clone()).or_insert(0) += 1;
vocabulary.insert(term.clone());
}
}
}
Self {
docs,
indexed,
average,
frequency,
vocabulary,
}
}
pub fn docs(&self) -> &[SearchDoc] {
&self.docs
}
pub fn is_empty(&self) -> bool {
self.docs.is_empty()
}
fn idf(&self, field: usize, term: &str) -> f64 {
let n = f64::from(self.frequency[field].get(term).copied().unwrap_or(0));
let count = self.docs.len() as f64;
(1.0 + (count - n + IDF_SMOOTHING) / (n + IDF_SMOOTHING)).ln()
}
fn term_score(&self, doc: &Indexed, term: &str) -> f64 {
let mut score = 0.0;
for (field, weight) in FIELD_WEIGHTS.iter().enumerate() {
let Some(&tf) = doc.terms[field].get(term) else {
continue;
};
let tf = f64::from(tf);
let norm = tf + K1 * (1.0 - B + B * doc.lengths[field] as f64 / self.average[field]);
score += weight * self.idf(field, term) * (tf * (K1 + 1.0)) / norm;
}
score
}
fn expand(&self, word: &str, is_last: bool) -> Vec<String> {
let exact = self.vocabulary.contains(word);
if exact && !is_last {
return vec![word.to_string()];
}
let prefixed: Vec<String> = self
.vocabulary
.range(word.to_string()..)
.take_while(|term| term.starts_with(word))
.cloned()
.collect();
match (prefixed.is_empty(), exact) {
(false, _) => prefixed,
(true, true) => vec![word.to_string()],
(true, false) => Vec::new(),
}
}
fn score_document(
&self,
index: usize,
expansions: &[Vec<String>],
word_count: usize,
id_query: Option<&str>,
) -> Option<Hit> {
let doc = &self.indexed[index];
let mut score = 0.0;
let mut matched = 0usize;
for terms in expansions {
let best = terms
.iter()
.map(|term| self.term_score(doc, term))
.fold(0.0, f64::max);
matched += usize::from(best > 0.0);
score += best;
}
score *= (matched as f64 / word_count as f64).powi(2);
score += self.number_bonus(index, id_query);
(score > 0.0).then_some(Hit { index, score })
}
fn number_bonus(&self, index: usize, id_query: Option<&str>) -> f64 {
let Some(id) = id_query else {
return 0.0;
};
let Some(number) = self.docs[index].number else {
return 0.0;
};
let number = number.to_string();
if !number.starts_with(id) {
return 0.0;
}
if number == id {
EXACT_NUMBER_BONUS
} else {
PREFIX_NUMBER_BONUS
}
}
pub fn search(&self, query: &str, limit: usize) -> Vec<Hit> {
let words = tokenize(query);
if words.is_empty() {
return Vec::new();
}
let last_is_prefix = !query.ends_with(char::is_whitespace);
let expansions: Vec<Vec<String>> = words
.iter()
.enumerate()
.map(|(i, word)| self.expand(word, last_is_prefix && i == words.len() - 1))
.collect();
let trimmed = query.trim();
let digits = trimmed.strip_prefix('#').unwrap_or(trimmed);
let id_query =
(!digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())).then_some(digits);
let mut hits: Vec<Hit> = self
.indexed
.iter()
.enumerate()
.filter_map(|(index, _)| self.score_document(index, &expansions, words.len(), id_query))
.collect();
hits.sort_by(|a, b| {
b.score
.total_cmp(&a.score)
.then_with(|| natural_cmp(&self.docs[a.index].id, &self.docs[b.index].id))
});
hits.truncate(limit);
hits
}
}
pub fn natural_cmp(a: &str, b: &str) -> Ordering {
let mut a = a.chars().peekable();
let mut b = b.chars().peekable();
loop {
match (a.peek().copied(), b.peek().copied()) {
(None, None) => return Ordering::Equal,
(None, Some(_)) => return Ordering::Less,
(Some(_), None) => return Ordering::Greater,
(Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {
let take = |it: &mut std::iter::Peekable<std::str::Chars<'_>>| {
let mut run = String::new();
while let Some(c) = it.next_if(char::is_ascii_digit) {
run.push(c);
}
run
};
let (x, y) = (take(&mut a), take(&mut b));
let (xt, yt) = (x.trim_start_matches('0'), y.trim_start_matches('0'));
let order = xt.len().cmp(&yt.len()).then_with(|| xt.cmp(yt));
if order != Ordering::Equal {
return order;
}
}
(Some(x), Some(y)) => {
let order = x
.to_lowercase()
.cmp(y.to_lowercase())
.then_with(|| x.cmp(&y));
if order != Ordering::Equal {
return order;
}
a.next();
b.next();
}
}
}
}
#[cfg(test)]
mod tests {
use super::{SearchDoc, SearchIndex, natural_cmp, tokenize};
fn index() -> SearchIndex {
let doc = |id: u64, title: &str, parent: &str, kind: &str, state: &str| {
SearchDoc::new(id.to_string(), title)
.number(id)
.parent(parent)
.meta(format!("{kind} {state} Doe, Jane"))
};
SearchIndex::new(vec![
doc(
4904258,
"Automate Team onboarding (Job Lifecycle Eventing)",
"",
"Product Backlog Item",
"New",
),
doc(
4904302,
"Assign tenant receiver access with the HANK module",
"Automate Team onboarding (Job Lifecycle Eventing)",
"Task",
"To Do",
),
doc(
4958950,
"Prove the integrated job journey in Azure Monitor",
"",
"Task",
"Done",
),
doc(
4959313,
"Enforce EVA complexity rules in prek",
"",
"Task",
"To Do",
),
])
}
fn ids(index: &SearchIndex, query: &str) -> Vec<String> {
index
.search(query, 20)
.into_iter()
.map(|hit| index.docs()[hit.index].id.clone())
.collect()
}
#[test]
fn tokenize_lowercases_strips_accents_and_stop_words() {
assert_eq!(
tokenize("The Café-Onboarding of EVA"),
["cafe", "onboarding", "eva"]
);
assert_eq!(
tokenize("file Wide"),
["file", "wide"],
"NFKD folds compatibility forms"
);
}
#[test]
fn the_last_word_matches_as_a_prefix_while_typing() {
let index = index();
assert_eq!(ids(&index, "onbo")[0], "4904258");
assert_eq!(ids(&index, "job onbo"), ["4904258", "4904302", "4958950"]);
}
#[test]
fn parent_titles_make_children_findable_below_the_parent() {
assert_eq!(ids(&index(), "onboarding"), ["4904258", "4904302"]);
}
#[test]
fn items_matching_more_words_rank_first() {
assert_eq!(ids(&index(), "azure journey")[0], "4958950");
}
#[test]
fn numbers_match_ids_by_prefix_and_exact_ids_rank_first() {
let index = index();
assert_eq!(ids(&index, "4958950")[0], "4958950");
assert_eq!(ids(&index, "#4958950")[0], "4958950");
assert_eq!(ids(&index, "49043"), ["4904302"]);
}
#[test]
fn empty_queries_return_nothing_and_the_limit_holds() {
let index = index();
assert!(ids(&index, " ").is_empty());
assert!(ids(&index, "the of").is_empty());
assert_eq!(index.search("task", 2).len(), 2);
}
#[test]
fn ids_compare_numbers_as_numbers() {
use std::cmp::Ordering::Less;
assert_eq!(natural_cmp("item-9", "item-10"), Less);
assert_eq!(natural_cmp("a", "B"), Less);
}
}