搜标题中间的词,
completionsuggester 补全不到。根因是completion是前缀 suggester,只匹配文本开头——「Gone with the Wind」搜wind(中间词)匹配不到,只有搜gone(开头)才补全。要匹配中间词(infix),得用search_as_you_type字段或 n-gram 分析器。
Issue & Env(案发现场与环境)
- 业务场景:搜索框里用户输入
wind,想补全出「Gone with the Wind」,但completion只补全出「Windmill Valley」(以 wind 开头的),「Gone with the Wind」这种 wind 在中间的补全不出来。 - 环境:OpenSearch 3.x(Docker latest),索引
movies_suggest,suggest是completion。 - 关键区分:前缀匹配 vs 中缀(infix)匹配——completion 只有前者。
StackTrace(返回体现状)
搜 wind,只返回以 wind 开头的候选:
{
"suggest" : {
"movie-suggest" : [
{
"text" : "wind",
"options" : [
{ "text" : "Windmill Valley" }
]
}
]
}
}
「Gone with the Wind」没出现——因为它的开头是 Gone,不是 wind。
Reproduce(复现代码)
# completion 搜中间词 wind → 只补全 Windmill Valley,不补全 Gone with the Wind
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": "wind", "completion": { "field": "suggest" } } } }'
判定标准:options 里只有「Windmill Valley」,没有「Gone with the Wind」。
Root Cause(根因分析)
completion 是前缀 suggester
官方文档明确:completion suggester 是「prefix suggester, so it matches the beginning of text only」。它只比较候选值开头和你输入的前缀,中间的词不在匹配范围。这是它快(内存 FST)的代价——只建了「开头 → 候选」的索引。
infix 匹配是另一条路线
要「输入中间词也能补全」,有两条路:① search_as_you_type 字段类型——它自动建 _2gram/_3gram/_index_prefix 子字段,天然支持前缀 + 中缀匹配;② 自建 n-gram 分析器 + 普通 match 查询。
The Fix(解决方案)
方案一:换 search_as_you_type(推荐,无需预索引建议)
curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/movies_sayt?pretty" \
-H "Content-Type: application/json" \
-d '{ "mappings": { "properties": { "title": { "type": "search_as_you_type" } } } }'
curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_sayt/_search?pretty" \
-H "Content-Type: application/json" \
-d '{ "query": { "multi_match": { "query": "wind", "type": "bool_prefix", "fields": ["title", "title._2gram", "title._3gram"] } } }'
search_as_you_type 用普通 _search 查询(不是 suggest),能匹配中间词。
方案二:保留 completion,但把每个词也单独灌一个 input
如果坚持用 completion,把标题拆成多个候选值灌进去(suggest 传数组),让每个词都成为一个「开头」:
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":"2"}}
{"suggest":["Gone with the Wind","the Wind","Wind"],"title":"Gone with the Wind"}
'
注意事项
- completion 用内存 FST,快但占内存;search_as_you_type 用 n-gram 子字段,占磁盘但不用预索引建议。
- 完整用法见 从零跑通 OpenSearch 搜索建议与自动补全。
References(参考来源)
- Completion field type — OpenSearch 官方文档opensearch-docs
- Search-as-you-type field type — OpenSearch 官方文档opensearch-docs
