传了
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
