Implement fielded Telegram search with a pluggable index store
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
use std::collections::BTreeSet;
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
|
||||
pub(crate) fn normalize(text: &str) -> String {
|
||||
text.nfkc()
|
||||
.flat_map(char::to_lowercase)
|
||||
.collect::<String>()
|
||||
.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
fn han(c: char) -> bool {
|
||||
matches!(c as u32, 0x3400..=0x4dbf | 0x4e00..=0x9fff | 0xf900..=0xfaff | 0x20000..=0x323af)
|
||||
}
|
||||
|
||||
// Keep individual Han characters in the index for one-character queries;
|
||||
// for longer Han runs query only the more selective overlapping bigrams.
|
||||
fn tokens(text: &str, indexing: bool) -> Vec<String> {
|
||||
let mut output = Vec::new();
|
||||
let mut chars = text.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if han(c) {
|
||||
let mut previous = c;
|
||||
let mut single = true;
|
||||
if indexing {
|
||||
output.push(c.to_string());
|
||||
}
|
||||
while let Some(next) = chars.next_if(|&n| han(n)) {
|
||||
output.push(format!("{previous}{next}"));
|
||||
if indexing {
|
||||
output.push(next.to_string());
|
||||
}
|
||||
single = false;
|
||||
previous = next;
|
||||
}
|
||||
if single && !indexing {
|
||||
output.push(c.to_string());
|
||||
}
|
||||
} else if c.is_alphanumeric() || c == '_' {
|
||||
let mut word = String::from(c);
|
||||
while let Some(next) = chars.next_if(|&n| !han(n) && (n.is_alphanumeric() || n == '_'))
|
||||
{
|
||||
word.push(next);
|
||||
}
|
||||
output.push(word);
|
||||
}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
pub(crate) fn index_tokens(text: &str) -> Vec<String> {
|
||||
tokens(text, true)
|
||||
}
|
||||
|
||||
pub(crate) fn query_terms(text: &str) -> BTreeSet<String> {
|
||||
tokens(text, false).into_iter().collect()
|
||||
}
|
||||
Reference in New Issue
Block a user