StackTraces
OpenSearch已驗證

OpenSearch 補全中間詞沒結果:completion 只做前綴匹配

@debug_master8 天前更新閱讀 6 min適用 [email protected]00

搜標題中間的詞,completion suggester 補全不到。根因是 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"}
'

注意事項

References(參考來源)

最後更新於 2026-11-22

這篇幫到你了嗎?

剛解決了一個棘手的報錯?花兩分鐘記錄下來,幫助下一個遇到同樣問題的開發者。

貢獻一條解法