Explorar o código

✨ (search): 多词检索按词的罕见度加权,记录召回评测与下一波计划

- fuzzy / definition 的单词子句乘 IDF 罕见度权重(归一后 4 次幂,下限 0.2),
  常见词不再淹没罕见的目标词;文档频率一次 _msearch 取齐、逐词缓存一天
- 词序子句(整句、相邻两词)不加权;单个词、CJK、exact/semantic/hybrid 不受影响
- documents/search-recall.md:评测方法、148 题留出集结果、向量/混合检索等下一波计划

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda hai 5 días
pai
achega
202750c7cd

+ 149 - 12
api-v13/app/Services/OpenSearchService.php

@@ -728,6 +728,12 @@ class OpenSearchService
         // ---------- 查询部分 ----------
         $queryText = trim($params['query'] ?? '');
 
+        // fuzzy / definition 的巴利文多词查询按词的罕见度加权;其余模式不需要
+        $weights = null;
+        if ($queryText !== '' && ! in_array($mode, ['exact', 'semantic', 'hybrid'], true) && ! $this->isCjkQuery($queryText)) {
+            $weights = $this->wordRarityWeights($this->scoringWords($this->splitQueryWords($queryText)));
+        }
+
         if ($queryText === '') {
             $query = ['match_all' => new \stdClass];
         } else {
@@ -745,12 +751,12 @@ class OpenSearchService
                     break;
 
                 case 'definition':
-                    $query = $this->buildDefinitionQuery($queryText);
+                    $query = $this->buildDefinitionQuery($queryText, $weights);
                     break;
 
                 case 'fuzzy':
                 default:
-                    $query = $this->buildFuzzyQuery($queryText);
+                    $query = $this->buildFuzzyQuery($queryText, $weights);
                     break;
             }
         }
@@ -876,9 +882,10 @@ class OpenSearchService
      *   - 巴利文(拉丁字母)→ 走三层排序(见 buildPaliFuzzyQuery)+ bold_* 提权
      *
      * @param  string  $query  搜索关键词
+     * @param  array<string, float>|null  $weights  巴利文各词的罕见度权重,null 表示都按 1
      * @return array OpenSearch DSL query 片段
      */
-    protected function buildFuzzyQuery(string $query): array
+    protected function buildFuzzyQuery(string $query, ?array $weights = null): array
     {
         if ($this->isCjkQuery($query)) {
             return [
@@ -896,7 +903,7 @@ class OpenSearchService
             ];
         }
 
-        return $this->buildPaliFuzzyQuery($query);
+        return $this->buildPaliFuzzyQuery($query, 1.0, $weights);
     }
 
     /**
@@ -955,6 +962,125 @@ class OpenSearchService
      */
     private const TIE_BREAKER_BOOST = 0.01;
 
+    /**
+     * 罕见度权重的下限:再常见的词也保留这么多分量,不至于完全不计
+     */
+    private const RARITY_WEIGHT_FLOOR = 0.2;
+
+    /**
+     * 罕见度权重的指数:IDF 取了对数,887 段与 211 段的词只差 0.82 : 1,拉不开;
+     * 归一后再取幂放大差距
+     */
+    private const RARITY_EXPONENT = 4;
+
+    /**
+     * 每个词的文档频率在 RedisCache 里的保存期(秒)。语料按月更新,一天足够新
+     */
+    private const DOC_FREQUENCY_TTL = 86400;
+
+    /**
+     * 多词查询里每个词的罕见度权重(类 BM25 的 IDF,按最罕见的词归一到 1)
+     *
+     * 按词计的固定分让每个词分量相同,常见词(如 bojjhaṅga,到处都是黑体)会把罕见的
+     * 目标词(dhammavicayasambojjhaṅga)挤出前排。乘上这个权重后,越罕见的词分越高。
+     * 文档频率按 title/content 的 .pali(带同义词,即全部词形)统计,一次 _msearch 取齐,
+     * 逐词缓存。取不到时返回全 1(等于不加权),只记日志不报错。
+     *
+     * @param  list<string>  $words  参与计分的原始词(已去掉停用词)
+     * @return array<string, float> 原始词 => 权重,范围 [RARITY_WEIGHT_FLOOR, 1]
+     */
+    protected function wordRarityWeights(array $words): array
+    {
+        $uniqueWords = array_values(array_unique($words));
+        $flat = array_fill_keys($uniqueWords, 1.0);
+
+        if (count($uniqueWords) < 2) {
+            return $flat;
+        }
+
+        try {
+            $index = config('mint.opensearch.index');
+            $total = RedisCache::remember("/opensearch/{$index}/doc-count", self::DOC_FREQUENCY_TTL, fn () => $this->count());
+            $frequencies = $this->documentFrequencies($index, $uniqueWords);
+        } catch (Exception $e) {
+            Log::warning('opensearch word rarity weights failed', ['words' => $uniqueWords, 'error' => $e->getMessage()]);
+
+            return $flat;
+        }
+
+        $idf = [];
+        foreach ($uniqueWords as $word) {
+            $df = $frequencies[$word] ?? 0;
+            $idf[$word] = log(1 + ($total - $df + 0.5) / ($df + 0.5));
+        }
+
+        $maxIdf = max($idf);
+        if ($maxIdf <= 0) {
+            return $flat;
+        }
+
+        return array_map(
+            fn (float $value): float => max(self::RARITY_WEIGHT_FLOOR, ($value / $maxIdf) ** self::RARITY_EXPONENT),
+            $idf,
+        );
+    }
+
+    /**
+     * 每个词出现在多少个文档里(含同义词展开的全部词形),逐词缓存,未缓存的一次 _msearch 取齐
+     *
+     * @param  string  $index  索引名
+     * @param  list<string>  $words  原始词
+     * @return array<string, int> 原始词 => 文档数
+     */
+    protected function documentFrequencies(string $index, array $words): array
+    {
+        $frequencies = [];
+        $missing = [];
+
+        foreach ($words as $word) {
+            $cached = RedisCache::get($this->documentFrequencyCacheKey($index, $word));
+            if ($cached === null) {
+                $missing[] = $word;
+            } else {
+                $frequencies[$word] = (int) $cached;
+            }
+        }
+
+        if ($missing === []) {
+            return $frequencies;
+        }
+
+        $body = [];
+        foreach ($missing as $word) {
+            $body[] = ['index' => $index];
+            $body[] = [
+                'size' => 0,
+                'track_total_hits' => true,
+                'query' => ['multi_match' => ['query' => $word, 'fields' => ['title.text.pali', 'content.text.pali']]],
+            ];
+        }
+
+        $responses = $this->client->msearch(['body' => $body])['responses'] ?? [];
+
+        foreach ($missing as $i => $word) {
+            $df = (int) ($responses[$i]['hits']['total']['value'] ?? 0);
+            $frequencies[$word] = $df;
+            RedisCache::put($this->documentFrequencyCacheKey($index, $word), $df, self::DOC_FREQUENCY_TTL);
+        }
+
+        return $frequencies;
+    }
+
+    /**
+     * @param  string  $index  索引名
+     * @param  string  $word  原始词
+     * @return string 文档频率的缓存 key
+     */
+    protected function documentFrequencyCacheKey(string $index, string $word): string
+    {
+        return "/opensearch/{$index}/word-df/".md5(mb_strtolower($word));
+    }
+
     /**
      * 巴利文停用词(小写;比较前去掉标点)
      *
@@ -1037,11 +1163,15 @@ class OpenSearchService
      * 不生成单词子句,也不进 BM25 子句,于是只命中「ca」的文档不会被召回。
      * 两个停用词组成的相邻词对同理跳过。查询全是停用词时按普通词处理。
      *
+     * 单词子句(拼写、同义词)乘上该词的罕见度权重(见 wordRarityWeights),
+     * 常见词分量小、罕见词分量大;词序子句(整句、相邻两词)不乘。
+     *
      * @param  string  $query  搜索关键词
      * @param  float  $scale  整体缩放(definition 模式用它把正文得分压到黑体字之下)
+     * @param  array<string, float>|null  $weights  原始词 => 罕见度权重,null 表示都按 1
      * @return array OpenSearch DSL query 片段
      */
-    protected function buildPaliFuzzyQuery(string $query, float $scale = 1.0): array
+    protected function buildPaliFuzzyQuery(string $query, float $scale = 1.0, ?array $weights = null): array
     {
         $words = $this->splitQueryWords($query);
         $wordCount = count($words);
@@ -1088,22 +1218,24 @@ class OpenSearchService
             }
         }
 
-        // 拼写:每个词各算一次(停用词不算)
+        // 拼写:每个词各算一次(停用词不算),按罕见度加权
         foreach ($scoringWords as $word) {
+            $weight = $weights[$word] ?? 1.0;
+
             $should[] = $this->constantScore([
                 'multi_match' => [
                     'query' => $word,
                     'fields' => $exactFields,
                     'operator' => 'and',
                 ],
-            ], $scores['exact']);
+            ], $scores['exact'] * $weight);
 
             $should[] = $this->constantScore([
                 'multi_match' => [
                     'query' => $word,
                     'fields' => $fuzzyFields,
                 ],
-            ], $scores['synonym']);
+            ], $scores['synonym'] * $weight);
         }
 
         // 同分文档按 BM25 排先后
@@ -1147,12 +1279,15 @@ class OpenSearchService
      *     正文里粘了连音(如 vitakkanti)匹配不到的词,往往靠它召回
      *   - 用 match_phrase 而不是 match:中文在 standard 下按字切分,phrase 要求字连续,
      *     避免一个字重合就命中
+     *   - 每个词的黑体分乘上它的罕见度权重(见 wordRarityWeights):常见词(bojjhaṅga)
+     *     不再与罕见的目标词(dhammavicayasambojjhaṅga)同分,挤占前排
      * 计分表见 DEFINITION_SCORES;正文部分复用 fuzzy 的计分,乘 DEFINITION_TEXT_SCALE。
      *
      * @param  string  $query  搜索关键词
+     * @param  array<string, float>|null  $weights  原始词 => 罕见度权重,null 表示都按 1
      * @return array OpenSearch DSL query 片段
      */
-    protected function buildDefinitionQuery(string $query): array
+    protected function buildDefinitionQuery(string $query, ?array $weights = null): array
     {
         $words = $this->splitQueryWords($query);
 
@@ -1164,14 +1299,16 @@ class OpenSearchService
 
         // 停用词不单独算黑体分(整句的 multi_phrase 仍带上它们)
         foreach ($this->scoringWords($words) as $word) {
+            $weight = $weights[$word] ?? 1.0;
+
             foreach (['single' => 'bold_single', 'multi' => 'bold_multi'] as $tier => $field) {
                 $should[] = $this->constantScore(
                     ['match_phrase' => [$field => $word]],
-                    self::DEFINITION_SCORES[$tier],
+                    self::DEFINITION_SCORES[$tier] * $weight,
                 );
                 $should[] = $this->constantScore(
                     ['match_phrase' => [$field => ['query' => $word, 'analyzer' => 'standard']]],
-                    self::DEFINITION_SCORES[$tier.'_exact'],
+                    self::DEFINITION_SCORES[$tier.'_exact'] * $weight,
                 );
             }
         }
@@ -1193,7 +1330,7 @@ class OpenSearchService
                 ],
             ];
         } else {
-            $should[] = $this->buildPaliFuzzyQuery($query, self::DEFINITION_TEXT_SCALE);
+            $should[] = $this->buildPaliFuzzyQuery($query, self::DEFINITION_TEXT_SCALE, $weights);
         }
 
         return [

+ 134 - 0
api-v13/documents/search-recall.md

@@ -0,0 +1,134 @@
+# 巴利文检索召回优化
+
+服务对象是 agent(问藏后端、wikipali-plugins):它们按问题选几个巴利词去检索,读前若干段回答。
+召回差就答不出来,或拿不相干的段落凑答案。本文记录已做的优化、评测方法与结果,以及下一波计划。
+
+相关代码:`app/Services/OpenSearchService.php`(`search()` 及 `build*Query`、`wordRarityWeights`),
+测试 `tests/Feature/OpenSearchQueryBuilderTest.php`;插件 `wikipali find` / `phrase`。
+
+## 一、现状(2026-11)
+
+### 检索入口
+
+| 入口 | 做法 | 擅长 |
+| --- | --- | --- |
+| `v2/search-pali-wbw` | 一个词的全部词形(`v2/case` 展开)在 `wbw_templates.real` 上 OR,按 `sum(weight)` 排 | 单个词查全;`bold=on` 只看黑体 |
+| `v3/search?search_mode=fuzzy` | 多词按原始词逐项累加固定分:整句原样、相邻两词原样、拼写相同、同义词可替代 | 几个概念同时出现的段落;找某句话 |
+| `v3/search?search_mode=definition` | 每个词命中单独黑体 / 多词黑体给分,正文只作次级排序 | 义注里把某词当词条解释的段落 |
+| 插件 `wikipali find` | 逐词 + fuzzy 按名次融合(RRF,k=60),前 3 段沿用逐词排序 | 回答具体问题的第一轮检索 |
+
+### 本波做了什么(社区实践 → 本项目的落地)
+
+1. **IDF 式罕见度加权**(BM25 的 IDF 公式):多词查询里常见词(到处是黑体的 `bojjhaṅga`)
+   与罕见的目标词同分,把前排占满。现在每个词的单词子句乘上罕见度权重:文档频率一次
+   `_msearch` 取齐、逐词缓存一天;IDF 取对数后差距太小,归一后再取 `RARITY_EXPONENT` 次幂;
+   下限 `RARITY_WEIGHT_FLOOR`。只作用于巴利文多词的 fuzzy / definition。
+2. **多路检索 + Reciprocal Rank Fusion**(RAG-Fusion):逐词检索与合并检索各有对方漏掉的题,
+   用 RRF 按名次合并(`1/(60+rank)` 相加),不用对齐两边分数的尺度。前 3 段(agent 读全文的
+   部分)沿用逐词检索的轮流排序,其余名额按 RRF 补入。实现在插件 `find`。
+3. **选词规则写进 agent 的规程**(query rewriting 的人工版):选答案段落里会出现的词、
+   引文用原文词形、列举类带成员、不用泛用词。只写原则,不写具体查询。
+
+## 二、评测方法
+
+两套评测,脚本见下节「复现」。
+
+- **调参集**(11 题):问藏里的典型问题。标准段落 = 答案必须同时出现的几个概念,各自用
+  `v2/case` 展开、`search-pali-wbw` 取全部段落再取交集——只用 v2 逐词表,不经 OpenSearch,
+  避免拿新接口给自己判卷。分两组跑:agent 当时实际选的词、选对的词。
+- **留出集**(150 题):问藏真实问题,排除调参集,固定种子随机抽。标准 = agent 历次回答里
+  实际引用过的段落坐标;关键词 = 该问题出现最多的 `pali_terms` 前 3 个。这个标准**偏向现状**
+  (引用本来就是现有检索找到的),新方法在这里持平即说明不倒退。
+
+指标:在**相同阅读窗口**(现状逐词检索合并后的段数)里命中几个标准段落;读全文的前 3 段命中几个;
+逐题统计相对现状「更好 / 持平 / 更差」。
+
+## 三、结果(2026-11-11)
+
+### 留出集(148 题,判定标准:大部分题更好或持平)
+
+融合方式离线比较(同一份检索结果,只换合并方法):
+
+| 方法 | 窗内命中 | 相对现状 好/平/差 | 前 3 命中 | 相对现状 好/平/差 |
+| --- | --- | --- | --- | --- |
+| 现状:逐词检索 | 296 | — | 88 | — |
+| 只用 definition | 200 | 18 / 67 / 63 | 74 | 27 / 83 / 38 |
+| 只用 fuzzy | 215 | 36 / 49 / 63 | 65 | 28 / 71 / 49 |
+| RRF 等权(逐词 + fuzzy + definition) | 311 | 31 / 98 / 19 | 80 | 24 / 93 / 31 |
+| **保头部 + RRF(逐词 + fuzzy)← 采用** | **325** | **33 / 100 / 15(89%)** | **88** | **0 / 148 / 0** |
+
+- 单用新接口都不如逐词,**只能补充,不能替代**。
+- 直接 RRF 会把前 3 段换掉;前 3 段是 agent 读全文的部分,标准又偏向现状,所以采用
+  「前 3 段沿用逐词的轮流排序,其余按 RRF」——窗内命中 +10%,前 3 段不变。
+- 再加 definition 一路没有额外收益(18 道定义类问题上也一样),所以 `find` 不放它。
+
+罕见度加权(指数 4 对比不加权,逐题):fuzzy 好 25 / 平 113 / 差 10,definition 好 24 / 平 117 / 差 7。
+指数 1 介于两者之间。采用指数 4。
+
+### 调参集(11 题)
+
+| 关键词 | 现状 窗内 / 前3 | `find` 窗内 / 前3 | 只用 fuzzy 窗内 |
+| --- | --- | --- | --- |
+| agent 当时选的词 | 21 / 5 | 20 / 5 | 26 |
+| 选对的词 | 28 / 8 | 33 / 8 | 80 |
+
+- 选词决定上限:同样是逐词检索,选对词从 5 题有命中提高到 8 题;这只能靠规程(选词规则)解决。
+- 选对词时,合并检索的增益明显(只用 fuzzy 窗内 80,约为现状的 3 倍);`find` 为了保住前 3 段,
+  只吸收了其中一部分。
+
+### 已知局限
+
+- 两套标准都是近似:调参集用「概念同时出现」代替人工相关性;留出集的引用来自现状检索,偏向现状。
+- 留出集的关键词是 agent 当时选的,没有体现新的选词规则——规则的效果要等 agent 用新规程重跑才能测。
+
+## 四、下一波:向量与混合检索
+
+本波只用现有索引能力。下面几项需要向量、模型或重建索引,放到下一波。
+
+### 4.1 混合检索:BM25 + 向量,RRF 融合
+
+- 索引已有 `content.vector` / `summary.vector` / `title.vector`(OpenAI embedding,1536 维,
+  faiss HNSW innerproduct),`search_mode=semantic` / `hybrid` 已存在。
+- 现在的 `hybrid` 是把 fuzzy 包成 `constant_score` 与 knn 分数直接相加,两边尺度不同,
+  权重靠 `fuzzy_ratio` / `semantic_ratio` 硬调。社区做法是按名次融合(RRF)。
+- OpenSearch 2.19 起有 `score-ranker-processor`(search pipeline 里的 RRF);本地是 2.18,
+  要么升级,要么在 PHP 里按名次合并(与插件 `find` 同一套算法)。
+- 价值:用户的中文问题可以直接召回巴利段落,**不再依赖 agent 选对巴利词**——这是评测里
+  头号瓶颈(调参集 11 题里 6 题因选词失败)。
+
+### 4.2 换领域向量模型
+
+- OpenAI 通用 embedding 对巴利文的效果没有评测过。Dharmamitra 发布了佛典专用的跨语言模型
+  (`buddhist-nlp/mitra-qwen35-embedder`,4096 维;2B 版 2048 维),支持巴利 / 梵 / 藏 / 汉互检,
+  模型卡称在跨语言检索上优于 BGE-M3、Qwen3-Embedding;**没有找到针对巴利文的公开评测**。
+- 做法:抽样几千段建临时索引,用本文的两套评测对比 OpenAI 与 MITRA,再决定是否全量重算。
+- 维度变化要重建 knn 字段(新索引 + 别名切换)。
+
+### 4.3 重排(rerank)
+
+- agent 只读前 3 段全文;融合后取前 50–150 段,用 cross-encoder(多语言如 bge-reranker-v2-m3)
+  或便宜的 LLM 对「问题 × 片段」逐段打分再排。重排只能调整顺序,找不回没召回的段落,
+  要放在 4.1 之后。
+
+### 4.4 段落补上下文(Contextual Retrieval)
+
+- 建索引时把章节路径(`path`)、段落标题拼进被检索的文本与向量输入;`summary.text` 现在是空的,
+  可放中文摘要。解决「答案段落里没有主语」(偈颂里没出现人名,人名只在章节标题里)。
+- 本波评测里试过只在查询时匹配 `path`:失败题的标准段落路径里没有可借力的词,收益不明显,
+  所以没做;随 4.1 一起在建索引时做。
+
+### 4.5 词根字段
+
+- 现在全部词形靠同义词词典(`pali_synonyms`)展开,词典缺词形(如 `vitakkāni`)、复合词与
+  连音(`koṭisanthāra`、`vassaṃvutthānaṃ`)会漏。`wbw_templates` 里已有拆好的词与词根,
+  可给每段写一个词根字段进索引,比维护同义词表可靠。需要重建索引。
+
+## 复现
+
+评测脚本目前放在开发机,没有进仓库:
+
+- `eval_questions.py`:调参集;`python3 -I eval_questions.py out.json [good]`
+- `eval_holdout.py`:留出集;`python3 -I eval_holdout.py qa_items.json out.json 150`
+- `qa_items.json`:从 `agent-poc/agent-tuning/data/raw/mail/*/body.txt` 抽出的问答条目
+
+都只调用本地 API(`http://127.0.0.1:8000/api`)。

+ 45 - 0
api-v13/tests/Feature/OpenSearchQueryBuilderTest.php

@@ -1,11 +1,20 @@
 <?php
 
+use App\Facades\RedisCache;
 use App\Services\OpenSearchService;
 
 /**
  * 调用 OpenSearchService 的 protected 查询构造方法(纯函数,不连 OpenSearch)
  */
 function buildSearchQuery(string $method, mixed ...$args): array
+{
+    return callSearchService($method, ...$args);
+}
+
+/**
+ * 调用 OpenSearchService 的 protected 方法,返回值不限类型
+ */
+function callSearchService(string $method, mixed ...$args): mixed
 {
     $service = new OpenSearchService;
 
@@ -106,3 +115,39 @@ it('ignores stopwords for definition bold scoring', function () {
     // 只有 vitakko 四条 + 整句在多词黑体里 30
     expect(constantScoreBoosts($query))->toEqual([100.0, 10.0, 30.0, 5.0, 30.0]);
 });
+
+/**
+ * 预置文档总数与各词的文档频率,让 wordRarityWeights 不用连 OpenSearch
+ *
+ * @param  array<string, int>  $frequencies  原始词 => 文档数
+ */
+function seedDocumentFrequencies(int $total, array $frequencies): void
+{
+    $index = config('mint.opensearch.index');
+    RedisCache::put("/opensearch/{$index}/doc-count", $total);
+    foreach ($frequencies as $word => $df) {
+        RedisCache::put(callSearchService('documentFrequencyCacheKey', $index, $word), $df);
+    }
+}
+
+it('weights rarer words higher and floors very common ones', function () {
+    seedDocumentFrequencies(550000, ['rare' => 10, 'mid' => 100, 'common' => 200000]);
+
+    $weights = buildSearchQuery('wordRarityWeights', ['rare', 'mid', 'common']);
+
+    expect($weights['rare'])->toBe(1.0)
+        ->and($weights['mid'])->toBeLessThan(1.0)->toBeGreaterThan(0.2)
+        ->and($weights['common'])->toBe(0.2);
+});
+
+it('does not weight a single word', function () {
+
+    expect(buildSearchQuery('wordRarityWeights', ['vitakko']))->toBe(['vitakko' => 1.0]);
+});
+
+it('multiplies per-word clauses by rarity but not word-order clauses', function () {
+    $query = buildSearchQuery('buildPaliFuzzyQuery', 'evaṃ me sutaṃ', 1.0, ['evaṃ' => 0.5, 'me' => 1.0, 'sutaṃ' => 0.25]);
+
+    // 整句 20 与相邻词对 5 不乘;拼写 10、同义 2 分别乘 0.5 / 1 / 0.25
+    expect(constantScoreBoosts($query))->toEqual([20.0, 5.0, 5.0, 5.0, 1.0, 10.0, 2.0, 2.5, 0.5]);
+});