StackTraces
OpenSearch已验证

OpenSearch 自动补全没结果:completion 字段或 suggest 用法不对

@debug_master8 天前更新阅读 6 min适用 [email protected]00

传了 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" } } } }'

注意事项

References(参考来源)

最后更新于 2026-11-22

这篇帮到你了吗?

刚解决了一个棘手的报错?花两分钟记录下来,帮助下一个遇到同样问题的开发者。

贡献一条解法