中文標題做
completion補全,輸入中文前綴補全不到、或結果不對。根因是completion字段預設用simple分析器——它按「非字母」切分 token,中文漢字被當成非字母,整串要麼被當成一個 token、要麼被逐字拆,前綴匹配就失效了。中文要顯式指定standard或 IK 分析器。
Issue & Env(案發現場與環境)
- 業務場景:中文電影標題(如「臥虎藏龍」)做補全,用戶輸入「臥」或「臥虎」,補全不到「臥虎藏龍」。
- 環境:OpenSearch 3.x(Docker latest),索引
movies_zh,suggest是completion(沒配 analyzer,用預設simple)。 - 關鍵區分:
simple分析器對中文無效——它按「非字母」切分,漢字不是英文字母,會被當成分隔符或整串保留。
StackTrace(返回體現狀)
輸入「臥」,options 空:
{
"suggest" : {
"movie-suggest" : [
{
"text" : "卧",
"options" : [ ]
}
]
}
}
中文前綴匹配不到,因為 simple 分析器沒把「臥虎藏龍」切成可前綴匹配的 token。
Reproduce(復現程式碼)
# completion 没配 analyzer,默认 simple,中文补全失效
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/movies_zh?pretty" \
-H "Content-Type: application/json" \
-d '{ "mappings": { "properties": { "suggest": { "type": "completion" }, "title": { "type": "keyword" } } } }'
curl -sk -u admin:Devfix@2026 -X POST "https://localhost:9200/movies_zh/_bulk?pretty" \
-H "Content-Type: application/x-ndjson" \
--data-binary '{"index":{"_id":"1"}}
{"suggest":"卧虎藏龙","title":"卧虎藏龙"}
'
curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_zh/_search?pretty" \
-H "Content-Type: application/json" \
-d '{ "suggest": { "movie-suggest": { "prefix": "卧", "completion": { "field": "suggest" } } } }'
判定標準:options 空,或補全結果和預期不符——因為 simple 分析器對中文的切分不對。
Root Cause(根因分析)
simple 分析器按「非字母」切分,中文不適用
completion 字段預設 analyzer: simple。simple 分析器把文本按「非字母字符」切成 token,只保留英文字母序列。中文漢字不是英文字母,在 simple 眼裡都是「非字母」,於是「臥虎藏龍」四個字要麼被整串保留成一個 token(前綴匹配只能整串匹配)、要麼被拆成不規則的 token——無論哪種,前綴補全都不對。
中文要用 standard 或 IK
standard分析器按 Unicode 文本分割,對中文會逐字切分(臥/虎/藏/龍),這樣「臥」能前綴匹配到「臥」這個 token,但「臥虎」這種連續漢字的前綴匹配仍不理想。- IK 分析器按中文詞切分(臥虎/藏龍),前綴匹配更符合中文習慣。本系列的中文篇已講 IK,見 從零跑通 OpenSearch 中文搜索。
The Fix(解決方案)
第一步:completion 字段顯式指定分析器
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/movies_zh?pretty" \
-H "Content-Type: application/json" \
-d '{ "mappings": { "properties": { "suggest": { "type": "completion", "analyzer": "standard" }, "title": { "type": "keyword" } } } }'
standard 會把中文逐字切,至少能按單字前綴補全;要按詞補全,換成 IK("analyzer": "ik_max_word",需先裝 IK 插件)。
第二步:search 端分析器同步
completion 有 search_analyzer 參數,預設等於 analyzer。如果搜索端和索引端分析器不一致,也會補全不到,可以顯式指定:
{ "suggest": { "type": "completion", "analyzer": "standard", "search_analyzer": "standard" } }
注意事項
simple是預設,對英文夠用;中文必須顯式換standard或 IK。- 中文詞級補全配合 IK 效果最好,插件安裝見 從零跑通 OpenSearch 中文搜索。
- 完整用法見 從零跑通 OpenSearch 搜索建議與自動補全。
References(參考來源)
- Completion field type — OpenSearch 官方文檔opensearch-docs
