| 1 | //! utopia-search: 内嵌 Tantivy 全文索引(jieba 中文分词)+ RRF 融合。 |
| 2 | //! 单索引多 KB:kb_id 作过滤字段;chunk 正文在 Postgres,索引里只存 id 映射。 |
| 3 | |
| 4 | mod docs; |
| 5 | pub use docs::{DocsIndex, DocsSection}; |
| 6 | |
| 7 | use std::collections::HashMap; |
| 8 | use std::path::Path; |
| 9 | use std::sync::Mutex; |
| 10 | |
| 11 | use anyhow::Context; |
| 12 | use tantivy::collector::TopDocs; |
| 13 | use tantivy::query::{BooleanQuery, Occur, Query, TermQuery}; |
| 14 | use tantivy::schema::{ |
| 15 | Field, IndexRecordOption, Schema, TextFieldIndexing, TextOptions, Value, STORED, STRING, |
| 16 | }; |
| 17 | use tantivy::tokenizer::TextAnalyzer; |
| 18 | use tantivy::{Index, IndexReader, IndexWriter, TantivyDocument, Term}; |
| 19 | |
| 20 | const JIEBA: &str = "jieba"; |
| 21 | const WRITER_HEAP: usize = 64 * 1024 * 1024; |
| 22 | |
| 23 | pub struct SearchIndex { |
| 24 | writer: Mutex<IndexWriter>, |
| 25 | reader: IndexReader, |
| 26 | analyzer: TextAnalyzer, |
| 27 | f_chunk_id: Field, |
| 28 | f_kb_id: Field, |
| 29 | f_document_id: Field, |
| 30 | f_text: Field, |
| 31 | } |
| 32 | |
| 33 | #[derive(Debug, Clone)] |
| 34 | pub struct Hit { |
| 35 | pub chunk_id: String, |
| 36 | pub score: f32, |
| 37 | } |
| 38 | |
| 39 | impl SearchIndex { |
| 40 | pub fn open(dir: &Path) -> anyhow::Result<Self> { |
| 41 | std::fs::create_dir_all(dir)?; |
| 42 | |
| 43 | let mut schema_builder = Schema::builder(); |
| 44 | let text_indexing = TextFieldIndexing::default() |
| 45 | .set_tokenizer(JIEBA) |
| 46 | .set_index_option(IndexRecordOption::WithFreqsAndPositions); |
| 47 | let f_chunk_id = schema_builder.add_text_field("chunk_id", STRING | STORED); |
| 48 | let f_kb_id = schema_builder.add_text_field("kb_id", STRING); |
| 49 | let f_document_id = schema_builder.add_text_field("document_id", STRING); |
| 50 | let f_text = schema_builder.add_text_field( |
| 51 | "text", |
| 52 | TextOptions::default().set_indexing_options(text_indexing), |
| 53 | ); |
| 54 | let schema = schema_builder.build(); |
| 55 | |
| 56 | let mmap = |
| 57 | tantivy::directory::MmapDirectory::open(dir).context("Failed to open index dir")?; |
| 58 | let index = |
| 59 | Index::open_or_create(mmap, schema).context("Failed to open/create Tantivy index")?; |
| 60 | index |
| 61 | .tokenizers() |
| 62 | .register(JIEBA, tantivy_jieba::JiebaTokenizer::new()); |
| 63 | |
| 64 | let writer = index.writer(WRITER_HEAP)?; |
| 65 | let reader = index.reader()?; |
| 66 | let analyzer = index |
| 67 | .tokenizers() |
| 68 | .get(JIEBA) |
| 69 | .context("jieba tokenizer 未注册")?; |
| 70 | |
| 71 | Ok(Self { |
| 72 | writer: Mutex::new(writer), |
| 73 | reader, |
| 74 | analyzer, |
| 75 | f_chunk_id, |
| 76 | f_kb_id, |
| 77 | f_document_id, |
| 78 | f_text, |
| 79 | }) |
| 80 | } |
| 81 | |
| 82 | /// 重建某文档的索引条目(先删后加,幂等),随后 commit。 |
| 83 | pub fn reindex_document( |
| 84 | &self, |
| 85 | kb_id: &str, |
| 86 | document_id: &str, |
| 87 | chunks: &[(String, String)], |
| 88 | ) -> anyhow::Result<()> { |
| 89 | let mut writer = self.writer.lock().expect("writer 锁中毒"); |
| 90 | writer.delete_term(Term::from_field_text(self.f_document_id, document_id)); |
| 91 | for (chunk_id, text) in chunks { |
| 92 | let mut doc = TantivyDocument::default(); |
| 93 | doc.add_text(self.f_chunk_id, chunk_id); |
| 94 | doc.add_text(self.f_kb_id, kb_id); |
| 95 | doc.add_text(self.f_document_id, document_id); |
| 96 | doc.add_text(self.f_text, text); |
| 97 | writer.add_document(doc)?; |
| 98 | } |
| 99 | writer.commit()?; |
| 100 | // 写后即可读:不等 reader 的异步重载窗口 |
| 101 | self.reader.reload()?; |
| 102 | Ok(()) |
| 103 | } |
| 104 | |
| 105 | pub fn delete_document(&self, document_id: &str) -> anyhow::Result<()> { |
| 106 | let mut writer = self.writer.lock().expect("writer 锁中毒"); |
| 107 | writer.delete_term(Term::from_field_text(self.f_document_id, document_id)); |
| 108 | writer.commit()?; |
| 109 | self.reader.reload()?; |
| 110 | Ok(()) |
| 111 | } |
| 112 | |
| 113 | /// 索引里有多少条分块。**启动时拿它跟库里的数对账**——索引目录是独立于 |
| 114 | /// 数据库的一份文件(换机器、卷没挂上、损坏都可能让它落空),而落空之后 |
| 115 | /// 检索只会静默回零,界面上看不出任何异样。 |
| 116 | pub fn len(&self) -> usize { |
| 117 | self.reader.searcher().num_docs() as usize |
| 118 | } |
| 119 | |
| 120 | pub fn is_empty(&self) -> bool { |
| 121 | self.len() == 0 |
| 122 | } |
| 123 | |
| 124 | /// BM25 检索(限定 kb)。 |
| 125 | /// 查询用与索引完全一致的 jieba analyzer 切词后按 OR 组合—— |
| 126 | /// 不能走 QueryParser:CJK 整句会被当成短语查询(要求词连续出现),召回归零。 |
| 127 | pub fn search(&self, kb_id: &str, query: &str, limit: usize) -> anyhow::Result<Vec<Hit>> { |
| 128 | let mut analyzer = self.analyzer.clone(); |
| 129 | let mut stream = analyzer.token_stream(query); |
| 130 | let mut term_queries: Vec<(Occur, Box<dyn Query>)> = Vec::new(); |
| 131 | while stream.advance() { |
| 132 | let token = stream.token(); |
| 133 | let word = token.text.trim(); |
| 134 | if word.is_empty() || word.chars().all(|c| !c.is_alphanumeric()) { |
| 135 | continue; |
| 136 | } |
| 137 | term_queries.push(( |
| 138 | Occur::Should, |
| 139 | Box::new(TermQuery::new( |
| 140 | Term::from_field_text(self.f_text, word), |
| 141 | IndexRecordOption::WithFreqs, |
| 142 | )), |
| 143 | )); |
| 144 | } |
| 145 | if term_queries.is_empty() { |
| 146 | return Ok(Vec::new()); |
| 147 | } |
| 148 | |
| 149 | let kb_filter: Box<dyn Query> = Box::new(TermQuery::new( |
| 150 | Term::from_field_text(self.f_kb_id, kb_id), |
| 151 | IndexRecordOption::Basic, |
| 152 | )); |
| 153 | let text_query: Box<dyn Query> = Box::new(BooleanQuery::new(term_queries)); |
| 154 | let combined = BooleanQuery::new(vec![(Occur::Must, kb_filter), (Occur::Must, text_query)]); |
| 155 | |
| 156 | let searcher = self.reader.searcher(); |
| 157 | let collector = TopDocs::with_limit(limit).order_by_score(); |
| 158 | let top = searcher.search(&combined, &collector)?; |
| 159 | let mut hits = Vec::with_capacity(top.len()); |
| 160 | for (score, addr) in top { |
| 161 | let doc: TantivyDocument = searcher.doc(addr)?; |
| 162 | if let Some(chunk_id) = doc.get_first(self.f_chunk_id).and_then(|v| v.as_str()) { |
| 163 | hits.push(Hit { |
| 164 | chunk_id: chunk_id.to_string(), |
| 165 | score, |
| 166 | }); |
| 167 | } |
| 168 | } |
| 169 | Ok(hits) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | /// Reciprocal Rank Fusion:融合多路召回的排名(k=60 为经验常数)。 |
| 174 | pub fn rrf_fuse(lists: &[Vec<String>], limit: usize) -> Vec<String> { |
| 175 | const K: f64 = 60.0; |
| 176 | let mut scores: HashMap<String, f64> = HashMap::new(); |
| 177 | for list in lists { |
| 178 | for (rank, id) in list.iter().enumerate() { |
| 179 | *scores.entry(id.clone()).or_default() += 1.0 / (K + rank as f64 + 1.0); |
| 180 | } |
| 181 | } |
| 182 | let mut ranked: Vec<(String, f64)> = scores.into_iter().collect(); |
| 183 | ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); |
| 184 | ranked.into_iter().take(limit).map(|(id, _)| id).collect() |
| 185 | } |