实现 Telegram 中文词法搜索核心与 Bot 查询逻辑 #1

Merged
Zayden-Jung merged 4 commits from codex/01-search-engine into main 2026-12-02 13:09:29 +00:00
7 changed files with 620 additions and 16 deletions
Showing only changes of commit 61d9e6877a - Show all commits
Generated
+445
View File
@@ -2,6 +2,416 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler32"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234"
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "allocator-api2"
version = "0.2.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014"
[[package]]
name = "cc"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66"
dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
]
[[package]]
name = "cedarwood"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d910bedd62c24733263d0bed247460853c9d22e8956bd4cd964302095e04e90"
dependencies = [
"smallvec",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "crc32fast"
version = "1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
dependencies = [
"cfg-if",
]
[[package]]
name = "dary_heap"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe"
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "find-msvc-tools"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
]
[[package]]
name = "include-flate"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f677e494e19ac4aa62375916f64b496f6b2655964c7313231c959858608cd9eb"
dependencies = [
"include-flate-codegen",
"include-flate-compress",
]
[[package]]
name = "include-flate-codegen"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51d3749676b6129ea4cf1e75adfb280a2148f03113806cb68cd7775fdfc65edf"
dependencies = [
"include-flate-compress",
"proc-macro-error3",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "include-flate-compress"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "476a7e4feb3325e85ca85565893517e283a1e59d3c9b695c162791dead7f004d"
dependencies = [
"libflate",
"zstd",
]
[[package]]
name = "jieba-macros"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "348294e44ee7e3c42685da656490f8febc7359632544019621588902216da95c"
dependencies = [
"phf_codegen",
]
[[package]]
name = "jieba-rs"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "766bd7012aa5ba49411ebdf4e93bddd59b182d2918e085d58dec5bb9b54b7105"
dependencies = [
"cedarwood",
"include-flate",
"jieba-macros",
"phf",
"regex",
"rustc-hash",
]
[[package]]
name = "jobserver"
version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
dependencies = [
"getrandom",
"libc",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libflate"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "561a8da1a50e1428d3c51321dafeca849df992a5bb67720c386131234caba82e"
dependencies = [
"adler32",
"crc32fast",
"dary_heap",
"libflate_lz77",
"no_std_io2",
]
[[package]]
name = "libflate_lz77"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff7a10e427698aef6eef269482776debfef63384d30f13aad39a1a95e0e098fd"
dependencies = [
"hashbrown",
"no_std_io2",
"rle-decode-fast",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "no_std_io2"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003"
dependencies = [
"memchr",
]
[[package]]
name = "phf"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
dependencies = [
"phf_shared",
"serde",
]
[[package]]
name = "phf_codegen"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"
dependencies = [
"phf_generator",
"phf_shared",
]
[[package]]
name = "phf_generator"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
dependencies = [
"fastrand",
"phf_shared",
]
[[package]]
name = "phf_shared"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
dependencies = [
"siphasher",
]
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "proc-macro-error-attr3"
version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e564d14133360e1ae169ffde5da25881b5fa47261665b8e5713c212c27799da"
dependencies = [
"proc-macro2",
"quote",
]
[[package]]
name = "proc-macro-error3"
version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f0d4471b3436c22106b21913b1dda531558918ae9b7ec55d58aa84b43552233"
dependencies = [
"proc-macro-error-attr3",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "regex"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "rle-decode-fast"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422"
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "siphasher"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
[[package]]
name = "smallvec"
version = "1.16.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "telefind-bot"
version = "0.1.0"
@@ -13,6 +423,7 @@ dependencies = [
name = "telefind-core"
version = "0.1.0"
dependencies = [
"jieba-rs",
"unicode-normalization",
]
@@ -22,6 +433,12 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "unicode-normalization"
version = "0.1.26"
@@ -30,3 +447,31 @@ checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
dependencies = [
"tinyvec",
]
[[package]]
name = "zstd"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "8.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.2.0+zstd.1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160"
dependencies = [
"cc",
"pkg-config",
]
+33 -14
View File
@@ -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)
}
+34
View File
@@ -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
);
}
+1
View File
@@ -4,4 +4,5 @@ version.workspace = true
edition.workspace = true
[dependencies]
jieba-rs = "0.8"
unicode-normalization = "0.1"
+21 -2
View File
@@ -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;
+73
View File
@@ -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]
);
}
}