在混合檢索裡給
title跑match,結果查不到預期文檔,或者匹配行為像「整詞精確」而非「分詞包含」。根因是match是全文查詢,需要text(會被分析器分詞)字段;而該字段在 mapping 裡被建成了keyword(不分詞、按原始值精確匹配)。
Issue & Env(案發現場與環境)
- 業務場景:跟著 從零跑通 OpenSearch 混合檢索 做 BM25 + k-NN 混合檢索,BM25 側用
match打在title上。但title沿用了上一篇 k-NN 篇的 mapping——那篇為了「只做向量檢索、不做全文分詞」,把title故意建成了keyword。 - 環境:OpenSearch 3.x(Docker latest 鏡像),單節點,索引
movies_hybrid(title誤為keyword,genre_vec為knn_vector)。 - 關鍵區分:
text會分詞 + 建倒排索引,keyword不分詞、整串存。
StackTrace(報錯原文 / 錯誤現象)
通常不報錯,但返回結果和預期不符——查「wind」這類詞,在 keyword 字段上 match 不會按詞命中包含該詞的文檔(除非整串恰好等於查詢詞):
{
"hits": {
"total": { "value": 0, "relation": "eq" },
"max_score": null,
"hits": []
}
}
(現象:match 打在 keyword 字段上,"wind" 匹配不到 "Gone with the Wind" / "Let the Wind Rise" 這類包含詞的文檔。)
Reproduce(復現程式碼)
索引把 title 建成 keyword,然後跑 match:
# 建索引:title 是 keyword(错误示范,混合检索 BM25 侧要 text)
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/movies_hybrid?pretty" \
-H "Content-Type: application/json" \
-d '{
"mappings": {
"properties": {
"title": { "type": "keyword" },
"genre_vec": { "type": "knn_vector", "dimension": 3, "space_type": "l2",
"method": { "name": "hnsw", "engine": "lucene" } }
}
}
}'
# 跑 match,查 "wind" 查不到包含词的文档
curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hybrid/_search?pretty" \
-H "Content-Type: application/json" \
-d '{ "query": { "match": { "title": "wind" } } }'
判定標準:match "wind" 應當命中標題裡包含 wind 的文檔(如 "Gone with the Wind")。命中為 0 或行為像精確匹配,即字段類型錯了。
Root Cause(根因分析)
match 是全文查詢,依賴分詞
match 屬於全文(full-text)查詢,它會把查詢詞用分析器分詞,再去倒排索引裡按詞(term)匹配。這個能力由 text 字段提供——text 字段在寫入時就被分析器切成詞條、建了倒排索引。
keyword 不分詞、按原始值精確匹配
keyword 字段把值當「一整串不可分割的字符串」存,不做分詞。match 打在 keyword 上時,語義退化成「整串是否相等」,查 "wind" 匹配不到 "Gone with the Wind"(整串不等於 wind)。
上篇故意用 keyword 的原因
從零跑通 OpenSearch k-NN 向量檢索 那篇只做向量檢索,title/genre 用 keyword 是為了「不做全文分詞、只當精確值/過濾鍵用」。到了混合檢索,BM25 側需要一個能分詞的 text 字段,所以得重建索引把 title 改成 text。
The Fix(解決方案)
方案一:把要跑 match 的字段建成 text(首選)
重建索引,title 用 text(預設 standard 分析器即可分詞),genre 保留 keyword 供精確過濾:
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/movies_hybrid?pretty" \
-H "Content-Type: application/json" \
-d '{
"settings": { "index.number_of_shards": 1, "index.number_of_replicas": 0 },
"mappings": {
"properties": {
"title": { "type": "text" },
"year": { "type": "integer" },
"genre": { "type": "keyword" },
"genre_vec": { "type": "knn_vector", "dimension": 3, "space_type": "l2",
"method": { "name": "hnsw", "engine": "lucene" } }
}
}
}'
方案二:同一字段建 text + keyword 雙類型(按需)
既要全文匹配、又要精確值(排序/聚合/過濾),用 multi-field 同時掛兩種類型:
"title": {
"type": "text",
"fields": { "raw": { "type": "keyword" } }
}
之後 match 打在 title(text),精確操作打在 title.raw(keyword)。
注意事項
text與keyword是 mapping 的一部分,改類型要重建索引(不能原地改),改完重新灌數據。- 混合檢索裡
match走text、knn走knn_vector,兩者互不干擾。 - 完整混合檢索用法見 從零跑通 OpenSearch 混合檢索。
References(參考來源)
- Match query — OpenSearch 官方文檔opensearch-docs
- Text and keyword field types — OpenSearch 官方文檔opensearch-docs
