傳了
suggest,返回裡options卻是空陣列。根因通常有三:①completion補全要用專門的completion字段類型,普通text/keyword字段不能拿來做suggest;② 補全列表要提前灌進索引(completion在索引期建記憶體 FST,不是查詢時現算);③ 它只匹配文本開頭,搜中間詞匹配不到。
Issue & Env(案發現場與環境)
- 業務場景:想做搜索框下拉補全,給
title建成text,直接拿它跑suggest,結果options空。 - 環境:OpenSearch 3.x(Docker latest),索引
movies,title是text。 - 關鍵區分:
suggest只認completion類型的字段;text字段走_search的普通 query,不走suggest。
StackTrace(返回體現狀)
對 text 字段跑 suggest,返回空 options:
{
"suggest" : {
"movie-suggest" : [
{
"text" : "the",
"offset" : 0,
"length" : 3,
"options" : [ ]
}
]
}
}
options 是空陣列——不是報錯,是「這個字段根本沒進補全索引」。
Reproduce(復現程式碼)
# title 是 text,直接拿它 suggest → 空
curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies/_search?pretty" \
-H "Content-Type: application/json" \
-d '{ "suggest": { "movie-suggest": { "prefix": "the", "completion": { "field": "title" } } } }'
判定標準:options 空陣列,因為 title 是 text 不是 completion。
Root Cause(根因分析)
suggest 只認 completion 字段
completion suggester 只工作在 completion 類型的字段上。text、keyword 字段沒有「補全索引」,跑 suggest 自然空。要補全,字段 mapping 裡必須是 "type": "completion"。
補全列表要提前灌
completion 字段在索引期把所有候選值建成記憶體 FST(有限狀態自動機),查詢時直接查這個結構,所以快;但也意味著「沒灌就沒有」。建好字段後,必須把候選值(如所有電影標題)作為文檔灌進去,suggest 才有東西可返回。
只匹配文本開頭
completion 是前綴 suggester,只匹配候選值的開頭。搜 the 能匹配 The Martian,搜中間的 martian 匹配不到。
The Fix(解決方案)
第一步:字段建成 completion
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/movies_suggest?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_suggest/_bulk?pretty" \
-H "Content-Type: application/x-ndjson" \
--data-binary '{"index":{"_id":"1"}}
{"suggest":"The Martian","title":"The Martian"}
{"index":{"_id":"2"}}
{"suggest":"The Matrix","title":"The Matrix"}
'
第三步:對 completion 字段跑 suggest
curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_suggest/_search?pretty" \
-H "Content-Type: application/json" \
-d '{ "suggest": { "movie-suggest": { "prefix": "the", "completion": { "field": "suggest" } } } }'
注意事項
- 搜中間詞補全不到是正常行為,要 infix 匹配用
search_as_you_type。 - 完整用法見 從零跑通 OpenSearch 搜索建議與自動補全。
References(參考來源)
- Completion field type — OpenSearch 官方文檔opensearch-docs
