Elffuss BraidHub

kikocis/utopia public

dev · 4.7 KiBRawPermalink
1//! 内置文档(Charter)的内存索引:启动时从打包 markdown 建,进程生命周期内只读。
2//! 协议中立——chat 的 search_docs 工具臂与将来的 MCP 工具面共用这一个入口。
3
4use anyhow::Context;
5use tantivy::collector::TopDocs;
6use tantivy::query::{BooleanQuery, Occur, Query, TermQuery};
7use tantivy::schema::{
8 Field, IndexRecordOption, Schema, TextFieldIndexing, TextOptions, Value, STORED,
9};
10use tantivy::tokenizer::TextAnalyzer;
11use tantivy::{Index, IndexReader, TantivyDocument, Term};
12
13const JIEBA: &str = "jieba";
14
15/// 一节文档(按 h2 切分;anchor 与前端 Docs 页的标题锚点同法生成)。
16#[derive(Debug, Clone)]
17pub struct DocsSection {
18 pub slug: String,
19 pub title: String,
20 pub heading: String,
21 pub anchor: String,
22 pub body: String,
23}
24
25pub struct DocsIndex {
26 reader: IndexReader,
27 analyzer: TextAnalyzer,
28 f_slug: Field,
29 f_title: Field,
30 f_heading: Field,
31 f_anchor: Field,
32 f_body: Field,
33 f_text: Field,
34}
35
36impl DocsIndex {
37 pub fn build(sections: &[DocsSection]) -> anyhow::Result<Self> {
38 let mut schema_builder = Schema::builder();
39 let text_indexing = TextFieldIndexing::default()
40 .set_tokenizer(JIEBA)
41 .set_index_option(IndexRecordOption::WithFreqsAndPositions);
42 let f_slug = schema_builder.add_text_field("slug", STORED);
43 let f_title = schema_builder.add_text_field("title", STORED);
44 let f_heading = schema_builder.add_text_field("heading", STORED);
45 let f_anchor = schema_builder.add_text_field("anchor", STORED);
46 let f_body = schema_builder.add_text_field("body", STORED);
47 // 检索域 = 节标题 + 正文(标题词权重靠重复出现自然获得)
48 let f_text = schema_builder.add_text_field(
49 "text",
50 TextOptions::default().set_indexing_options(text_indexing),
51 );
52 let schema = schema_builder.build();
53
54 let index = Index::create_in_ram(schema);
55 index
56 .tokenizers()
57 .register(JIEBA, tantivy_jieba::JiebaTokenizer::new());
58
59 let mut writer = index.writer(16 * 1024 * 1024)?;
60 for s in sections {
61 let mut doc = TantivyDocument::default();
62 doc.add_text(f_slug, &s.slug);
63 doc.add_text(f_title, &s.title);
64 doc.add_text(f_heading, &s.heading);
65 doc.add_text(f_anchor, &s.anchor);
66 doc.add_text(f_body, &s.body);
67 doc.add_text(f_text, format!("{}\n{}", s.heading, s.body));
68 writer.add_document(doc)?;
69 }
70 writer.commit()?;
71
72 let reader = index.reader()?;
73 let analyzer = index
74 .tokenizers()
75 .get(JIEBA)
76 .context("jieba tokenizer 未注册")?;
77 Ok(Self {
78 reader,
79 analyzer,
80 f_slug,
81 f_title,
82 f_heading,
83 f_anchor,
84 f_body,
85 f_text,
86 })
87 }
88
89 /// BM25 检索。切词方式与 SearchIndex 一致(手工 OR 组合,避开 CJK 短语查询陷阱)。
90 pub fn search(&self, query: &str, limit: usize) -> anyhow::Result<Vec<DocsSection>> {
91 let mut analyzer = self.analyzer.clone();
92 let mut stream = analyzer.token_stream(query);
93 let mut term_queries: Vec<(Occur, Box<dyn Query>)> = Vec::new();
94 while stream.advance() {
95 let word = stream.token().text.trim().to_string();
96 if word.is_empty() || word.chars().all(|c| !c.is_alphanumeric()) {
97 continue;
98 }
99 term_queries.push((
100 Occur::Should,
101 Box::new(TermQuery::new(
102 Term::from_field_text(self.f_text, &word),
103 IndexRecordOption::WithFreqs,
104 )),
105 ));
106 }
107 if term_queries.is_empty() {
108 return Ok(Vec::new());
109 }
110
111 let searcher = self.reader.searcher();
112 let top = searcher.search(
113 &BooleanQuery::new(term_queries),
114 &TopDocs::with_limit(limit).order_by_score(),
115 )?;
116 let get = |doc: &TantivyDocument, f: Field| {
117 doc.get_first(f)
118 .and_then(|v| v.as_str())
119 .unwrap_or_default()
120 .to_string()
121 };
122 let mut hits = Vec::with_capacity(top.len());
123 for (_score, addr) in top {
124 let doc: TantivyDocument = searcher.doc(addr)?;
125 hits.push(DocsSection {
126 slug: get(&doc, self.f_slug),
127 title: get(&doc, self.f_title),
128 heading: get(&doc, self.f_heading),
129 anchor: get(&doc, self.f_anchor),
130 body: get(&doc, self.f_body),
131 });
132 }
133 Ok(hits)
134 }
135}