Support segmented Chinese queries, phrase matching and type filters
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
use telefind_core::{Kind, Media, Query};
|
||||
pub(crate) enum Input<'a> {
|
||||
Ignore,
|
||||
Help,
|
||||
Search(telefind_core::Query<'a>),
|
||||
Search(Query<'a>),
|
||||
}
|
||||
|
||||
pub(crate) fn parse<'a>(bot: &str, text: &'a str) -> Input<'a> {
|
||||
@@ -10,7 +11,7 @@ pub(crate) fn parse<'a>(bot: &str, text: &'a str) -> Input<'a> {
|
||||
return Input::Ignore;
|
||||
}
|
||||
if !text.starts_with('/') {
|
||||
return Input::Search(telefind_core::Query::new(text));
|
||||
return search(text, 1);
|
||||
}
|
||||
let (command, args) = text.split_once(char::is_whitespace).unwrap_or((text, ""));
|
||||
let (command, target) = command
|
||||
@@ -21,23 +22,41 @@ pub(crate) fn parse<'a>(bot: &str, text: &'a str) -> Input<'a> {
|
||||
}
|
||||
match (command, args.trim()) {
|
||||
("/search", "") | ("/help" | "/start", _) => Input::Help,
|
||||
("/search", query) => Input::Search(telefind_core::Query::new(query)),
|
||||
("/search", query) => search(query, 1),
|
||||
("/page", args) => {
|
||||
let Some((number, text)) = args.split_once(char::is_whitespace) else {
|
||||
return Input::Help;
|
||||
};
|
||||
let mut query = telefind_core::Query::new(text.trim());
|
||||
let Some(offset) = number
|
||||
.parse::<usize>()
|
||||
.ok()
|
||||
.and_then(|n| n.checked_sub(1))
|
||||
.and_then(|n| n.checked_mul(query.limit))
|
||||
else {
|
||||
return Input::Help;
|
||||
};
|
||||
query.offset = offset;
|
||||
Input::Search(query)
|
||||
number
|
||||
.parse()
|
||||
.map_or(Input::Help, |page| search(text.trim(), page))
|
||||
}
|
||||
_ => Input::Ignore,
|
||||
}
|
||||
}
|
||||
|
||||
fn search(text: &str, page: usize) -> Input<'_> {
|
||||
let mut q = Query::new(text);
|
||||
if let Some(filter) = text.strip_prefix("type:") {
|
||||
let Some((kind, rest)) = filter.split_once(char::is_whitespace) else {
|
||||
return Input::Help;
|
||||
};
|
||||
q.text = rest.trim();
|
||||
match kind {
|
||||
"channel" => q.kind = Some(Kind::Channel),
|
||||
"group" => q.kind = Some(Kind::Group),
|
||||
"bot" => q.kind = Some(Kind::Bot),
|
||||
"post" => q.kind = Some(Kind::Post),
|
||||
"photo" => q.media = Some(Media::Photo),
|
||||
"video" => q.media = Some(Media::Video),
|
||||
"audio" => q.media = Some(Media::Audio),
|
||||
"file" => q.media = Some(Media::File),
|
||||
_ => return Input::Help,
|
||||
}
|
||||
}
|
||||
let Some(offset) = page.checked_sub(1).and_then(|p| p.checked_mul(q.limit)) else {
|
||||
return Input::Help;
|
||||
};
|
||||
q.offset = offset;
|
||||
Input::Search(q)
|
||||
}
|
||||
|
||||
@@ -68,3 +68,37 @@ fn paging_is_stateless_and_rejects_invalid_numbers() {
|
||||
assert_eq!(handle(&index, "me", text).unwrap(), Reply::Help);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_filter_is_available_in_search_and_page_commands() {
|
||||
let mut index = MemoryIndex::default();
|
||||
for (id, media) in [(1, None), (2, Some(telefind_core::Media::Video))] {
|
||||
index
|
||||
.upsert(Document {
|
||||
id: DocumentId::Post {
|
||||
chat: 1,
|
||||
message: id,
|
||||
},
|
||||
username: PublicName::new("demo_feed").unwrap(),
|
||||
title: "教程".into(),
|
||||
body: String::new(),
|
||||
media,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
for query in [
|
||||
"type:video 教程",
|
||||
"/search type:video 教程",
|
||||
"/page 1 type:video 教程",
|
||||
] {
|
||||
let Reply::Results { links, total } = handle(&index, "me", query).unwrap() else {
|
||||
panic!("expected results")
|
||||
};
|
||||
assert_eq!(total, 1);
|
||||
assert_eq!(links[0].url, "https://t.me/demo_feed/2");
|
||||
}
|
||||
assert_eq!(
|
||||
handle(&index, "me", "/search type:unknown 教程").unwrap(),
|
||||
Reply::Help
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,4 +4,5 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
jieba-rs = "0.8"
|
||||
unicode-normalization = "0.1"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use std::collections::BTreeSet;
|
||||
use jieba_rs::Jieba;
|
||||
use std::{collections::BTreeSet, sync::OnceLock};
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
|
||||
pub(crate) fn normalize(text: &str) -> String {
|
||||
@@ -54,5 +55,23 @@ pub(crate) fn index_tokens(text: &str) -> Vec<String> {
|
||||
}
|
||||
|
||||
pub(crate) fn query_terms(text: &str) -> BTreeSet<String> {
|
||||
tokens(text, false).into_iter().collect()
|
||||
static LEXICON: OnceLock<Jieba> = OnceLock::new();
|
||||
let mut terms = BTreeSet::new();
|
||||
let mut rest = text;
|
||||
while let Some(first) = rest.chars().next() {
|
||||
let is_han = han(first);
|
||||
let end = rest.find(|c: char| han(c) != is_han).unwrap_or(rest.len());
|
||||
let (run, tail) = rest.split_at(end);
|
||||
if is_han {
|
||||
// Segment only the query. The existing character/bigram postings can
|
||||
// match each dictionary word even in names absent from the dictionary.
|
||||
for word in LEXICON.get_or_init(Jieba::new).cut(run, false) {
|
||||
terms.extend(tokens(word, false));
|
||||
}
|
||||
} else {
|
||||
terms.extend(tokens(run, false));
|
||||
}
|
||||
rest = tail;
|
||||
}
|
||||
terms
|
||||
}
|
||||
|
||||
@@ -38,6 +38,13 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
|
||||
hits: Vec::new(),
|
||||
};
|
||||
let text = analysis::normalize(query.text);
|
||||
// Only closed quote pairs are operators; an unmatched trailing quote is punctuation.
|
||||
let parts: Vec<_> = text.split('"').skip(1).collect();
|
||||
let phrases: Vec<_> = parts
|
||||
.chunks_exact(2)
|
||||
.map(|pair| pair[0].trim())
|
||||
.filter(|phrase| !phrase.is_empty())
|
||||
.collect();
|
||||
let mut lists = Vec::new();
|
||||
for term in analysis::query_terms(&text) {
|
||||
let Some(postings) = reader.postings(&term)? else {
|
||||
@@ -66,6 +73,12 @@ pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<Sear
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if !phrases
|
||||
.iter()
|
||||
.all(|phrase| entry.title.contains(phrase) || entry.body.contains(phrase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
total += 1;
|
||||
if query.limit == 0 || query.offset >= first.len() {
|
||||
continue;
|
||||
|
||||
@@ -110,3 +110,76 @@ fn filtering_precedes_paging_and_ties_are_stable() {
|
||||
query.kind = Some(Kind::Bot);
|
||||
assert_eq!(index.search(&query).unwrap().total, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoted_phrase_requires_adjacency_in_a_single_field() {
|
||||
let mut index = MemoryIndex::default();
|
||||
for doc in [
|
||||
post(1, 1, "Rust Search", "入门"),
|
||||
post(1, 2, "Rust", "Search 入门"),
|
||||
post(1, 3, "Search Rust", "入门"),
|
||||
] {
|
||||
index.upsert(doc).unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
ids(&index, &Query::new("\"rust search\" 入门")),
|
||||
vec![DocumentId::Post {
|
||||
chat: 1,
|
||||
message: 1
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unspaced_chinese_query_matches_words_across_fields_and_keeps_model_required() {
|
||||
let mut index = MemoryIndex::default();
|
||||
index
|
||||
.upsert(post(1, 1, "上海", "二手 相机 RTX 5090"))
|
||||
.unwrap();
|
||||
index
|
||||
.upsert(post(1, 2, "上海", "二手 相机 RTX 5080"))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ids(&index, &Query::new("上海二手相机 5090")),
|
||||
vec![DocumentId::Post {
|
||||
chat: 1,
|
||||
message: 1
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "synthetic capacity measurement; run explicitly in release mode"]
|
||||
fn measure_ranked_queries_over_25000_posts() {
|
||||
use std::time::Instant;
|
||||
let mut index = MemoryIndex::default();
|
||||
let start = Instant::now();
|
||||
for id in 1..=25_000 {
|
||||
let title = format!("频道sku{} 相机 {}", id % 100, id % 50);
|
||||
index.upsert(post(1, id, &title, "摄影教程与设备")).unwrap();
|
||||
}
|
||||
let ingest = start.elapsed();
|
||||
let queries = ["相机", "sku3 3", "设备", "摄影教程 17"];
|
||||
for text in queries {
|
||||
let query = Query::new(text);
|
||||
let page = index.search(&query).unwrap();
|
||||
let expected = match text {
|
||||
"sku3 3" => 250,
|
||||
"摄影教程 17" => 500,
|
||||
_ => 25_000,
|
||||
};
|
||||
assert_eq!(page.total, expected);
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..30 {
|
||||
let start = Instant::now();
|
||||
let result = index.search(&query).unwrap();
|
||||
assert_eq!(result.hits.len(), 10);
|
||||
times.push(start.elapsed());
|
||||
}
|
||||
times.sort_unstable();
|
||||
println!(
|
||||
"records=25000 ingest={ingest:?} query={text:?} matches={expected} p50={:?} p95={:?}",
|
||||
times[14], times[28]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user