StackTraces
OpenSearch從零跑通

從零跑通 OpenSearch 高亮:6 步,外加 3 個容易卡住的地方

@debug_master2026-11-22適用 [email protected]

跟著這篇走完,你會把 OpenSearch 搜索結果「命中詞高亮」這件事配齊:用 highlight 把命中詞包上 <em>、用 fragment_size 控片段長度、用 number_of_fragments 控片段條數、用 pre_tags/post_tags 換自定義標籤,最後把長文本裁成搜索結果頁上那幾行帶高亮的摘要。整個過程 6 步,每步一條驗證命令。環境沿用從零跑通 OpenSearch 本地搜索服務:端口 9200、用戶 admin、密碼 Devfix@2026;你換了值替換掉就行。

先說清一個貫穿整篇的認知:highlight 不改你的數據。它和 Meilisearch 的 _formatted 副本是一個道理——高亮結果不寫回索引,而是引擎在返回體的每個 hit 裡額外放一個 highlight 物件,原始 _source 原樣保留。前端渲染高亮讀 highlight,存數據讀 _source。這篇預設你已經跑通了本地搜索服務,Docker 啟動、建索引、bulk 導入、curl 帶 -sk -u admin:Devfix@2026 的寫法全部複用,不再重複。如果你玩過從零跑通 Meilisearch 高亮與結果展示,這篇是對稱篇:同一個問題,Meilisearch 用搜索參數 attributesToHighlight,OpenSearch 用查詢 DSL 裡的 highlight 塊。

從零跑通 OpenSearch 高亮 6 步流程封面:建長文本索引 → 基本高亮 → 片段參數 → 自定義標籤 → 全字段 → 組合收場

前置條件

項 要求 說明
OpenSearch 3.x(Docker latest 鏡像) 單節點,security 開啟,HTTPS 端口 9200
前置文章 已跑通 opensearch-local-search 複用容器、密碼、curl 寫法
curl 任意版本 全文用 curl 調 REST API

先確認服務活著:

curl -sk -u admin:Devfix@2026 "https://localhost:9200"

返回裡有 cluster_name 就滿足條件。報連接失敗說明容器沒起來,回第一篇第二步。

第一步:建 movies_hl 索引,灌帶長 synopsis 的 5 條電影

高亮要演示「長文本裁成片段」,所以先得有長文本。建一個 movies_hl 索引,synopsis 是 text 類型、值是一兩百字符的劇情簡介(這是演示 fragment_size 的前提):

curl -sk -u admin:Devfix@2026 -X PUT "https://localhost:9200/movies_hl?pretty" \
  -H "Content-Type: application/json" \
  -d '{
    "settings": { "index.number_of_shards": 1, "index.number_of_replicas": 0 },
    "mappings": {
      "properties": {
        "title":    { "type": "text" },
        "year":     { "type": "integer" },
        "genre":    { "type": "keyword" },
        "synopsis": { "type": "text" }
      }
    }
  }'
{
  "acknowledged" : true,
  "shards_acknowledged" : true,
  "index" : "movies_hl"
}

灌 5 條電影,synopsis 刻意寫得夠長(超過預設片段長度 100 字符),第三步才看得出裁剪效果:

curl -sk -u admin:Devfix@2026 -X POST "https://localhost:9200/movies_hl/_bulk?pretty" \
  -H "Content-Type: application/x-ndjson" \
  --data-binary '{"index":{"_id":"1"}}
{"title":"Let the Wind Rise","year":2013,"genre":"drama","synopsis":"A young woman discovers she can control the wind during a devastating storm that threatens her coastal hometown. As the winds grow stronger with each passing day, she must learn to master her newfound power before the hurricane destroys everything she loves."}
{"index":{"_id":"2"}}
{"title":"Gone with the Wind","year":1939,"genre":"drama","synopsis":"Set against the backdrop of the American Civil War, this sweeping epic follows Scarlett O Hara as she navigates love, loss, and survival. From the burning of Atlanta to the rebuilding of Tara, her story spans years of hardship and quiet resilience."}
{"index":{"_id":"3"}}
{"title":"The Rise of Machines","year":2024,"genre":"sci-fi","synopsis":"In a near future where robots serve every human need, a rogue artificial intelligence begins taking over the global network. A small team of engineers races against the clock to shut it down before every machine on Earth turns against its creators."}
{"index":{"_id":"4"}}
{"title":"Windmill Valley","year":2020,"genre":"drama","synopsis":"A quiet farming community has relied on its windmills for generations, but when a mysterious corporation buys up the surrounding land, the villagers must fight back. One farmer daughter leads a stubborn resistance to save their way of life."}
{"index":{"_id":"5"}}
{"title":"The Martian","year":2015,"genre":"sci-fi","synopsis":"Stranded alone on Mars after a mission goes catastrophically wrong, an astronaut must draw on his ingenuity and a dwindling supply of resources to stay alive. Meanwhile, NASA scrambles to bring him home before the harsh red planet claims him."}
'
{
  "errors" : false,
  "items" : [ { "index" : { "_id" : "1", "status" : 201 } }, ... ]
}

errors 是 false、5 條都 201 就進去了。

驗證命令:

curl -sk -u admin:Devfix@2026 "https://localhost:9200/movies_hl/_count?pretty"
{
  "count" : 5,
  "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }
}

返回 "count": 5 就通過。

第二步:基本高亮——看 highlight 返回結構長什麼樣

先做最簡單的:搜 title 裡的 wind,高亮 title。highlight 是搜索請求體的頂層參數,和 query 平級(不是 query 的子字段):

curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hl/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{ "query": { "match": { "title": "wind" } }, "highlight": { "fields": { "title": {} } } }'
{
  "hits" : {
    "total" : { "value" : 2, "relation" : "eq" },
    "hits" : [
      {
        "_id" : "1",
        "_score" : 0.63,
        "_source" : { "title" : "Let the Wind Rise", "year" : 2013, "genre" : "drama" },
        "highlight" : {
          "title" : [ "Let the <em>Wind</em> Rise" ]
        }
      },
      {
        "_id" : "2",
        "_score" : 0.63,
        "_source" : { "title" : "Gone with the Wind", "year" : 1939, "genre" : "drama" },
        "highlight" : {
          "title" : [ "Gone with the <em>Wind</em>" ]
        }
      }
    ]
  }
}

三個觀察點,是後面的伏筆:

  • 多了個 highlight 物件。命中詞 Wind 被 <em>/</em> 包住,放在 highlight.title 裡。
  • highlight.title 是陣列,不是字符串——因為一個字段可能被切成多個片段(第三步就看到)。
  • 原始 _source.title 沒動。_source.title 還是乾淨的 Let the Wind Rise,不帶標籤。

所以前端渲染標題高亮讀 hit.highlight.title[0],存數據讀 hit._source.title,兩處各司其職。

驗證命令:

curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hl/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{ "query": { "match": { "title": "wind" } }, "highlight": { "fields": { "title": {} } } }' \
  | grep -o '<em>Wind</em>'

能 grep 到 <em>Wind</em> 就通過。

第三步:fragment_size + number_of_fragments 控制片段(承重步)

這是全文承重的一步。title 短,一句話就高亮完了;但 synopsis 有一兩百字符,搜索結果頁只要幾行摘要。這時兩個參數上場:fragment_size 定每個片段多少字符,number_of_fragments 定返回幾條片段。

先搜 synopsis 裡的 wind,高亮 synopsis,用 fragment_size: 60、number_of_fragments: 2:

curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hl/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{ "query": { "match": { "synopsis": "wind" } }, "highlight": { "fields": { "synopsis": { "fragment_size": 60, "number_of_fragments": 2 } } } }'
{
  "hits" : {
    "hits" : [
      {
        "_id" : "1",
        "_source" : { "title" : "Let the Wind Rise" },
        "highlight" : {
          "synopsis" : [
            "A young woman discovers she can control the <em>wind</em> during a devastating storm",
            "that threatens her coastal hometown. As the <em>wind</em>s grow stronger with each"
          ]
        }
      }
    ]
  }
}

逐段說清兩個參數:

  • fragment_size 是字符數,不是詞數。60 就是每個片段約 60 個字符。這是和 Meilisearch 的 cropLength(詞數)最不一樣的地方——OpenSearch 按字符,Meilisearch 按詞。兩個引擎同一件事,單位不同,見常見問題第 2 項。
  • number_of_fragments 是片段條數。2 就是最多返回 2 段,按相關度挑最相關的 2 段(不是從頭截前兩段)。
  • 高亮器按句子邊界切。預設 unified 高亮器儘量讓片段落在完整句子上,所以 fragment_size: 60 出來的片段可能比 60 字符略長一點(要把句子收完整)。

再看一個「整字段」的用法:number_of_fragments: 0 表示返回整個字段的高亮全文(不是「0 條片段」),此時 fragment_size 被忽略:

curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hl/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{ "query": { "match": { "synopsis": "wind" } }, "highlight": { "fields": { "synopsis": { "number_of_fragments": 0 } } } }'

返回的 highlight.synopsis[0] 是整個 synopsis 的完整文本,所有 wind 都被 <em> 包住。

驗證命令:

curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hl/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{ "query": { "match": { "synopsis": "wind" } }, "highlight": { "fields": { "synopsis": { "fragment_size": 60, "number_of_fragments": 2 } } } }' \
  | grep -o '<em>wind</em>'

能 grep 到 <em>wind</em> 就通過。

第四步:自定義標籤 pre_tags / post_tags

預設 <em> 夠用,但如果你用的是 <mark>、或想給高亮加 class,就換 pre_tags / post_tags(注意是陣列):

curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hl/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{ "query": { "match": { "title": "wind" } }, "highlight": { "pre_tags": [ "<mark>" ], "post_tags": [ "</mark>" ], "fields": { "title": {} } } }'
{
  "highlight" : {
    "title" : [ "Let the <mark>Wind</mark> Rise" ]
  }
}

<em> 換成了 <mark>。pre_tags/post_tags 是頂層 highlight 的參數(對 fields 裡所有字段生效),也可以放進單個字段裡只對那個字段生效。兩個標籤要成對換,只換一半會產出沒閉合的 HTML。

驗證命令:

curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hl/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{ "query": { "match": { "title": "wind" } }, "highlight": { "pre_tags": [ "<mark>" ], "post_tags": [ "</mark>" ], "fields": { "title": {} } } }' \
  | grep -o '<mark>Wind</mark>'

能 grep 到 <mark>Wind</mark> 就通過。

第五步:require_field_match——控制「只高亮查詢匹配的字段」

預設 require_field_match: true,意思是「只高亮查詢實際匹配到的字段」。搜 title 裡的 wind,卻想同時高亮 synopsis,預設會失敗(synopsis 沒被 match 查詢匹配到):

curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hl/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{ "query": { "match": { "title": "wind" } }, "highlight": { "fields": { "synopsis": {} } } }'

這條返回的 hit 裡沒有 highlight.synopsis——因為查詢只匹配了 title,synopsis 沒被匹配,預設不高亮它。這正是新手常踩的「我明明列了 synopsis 怎麼沒高亮」,見常見問題第 1 項。

要跨字段高亮,關掉它:

curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hl/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{ "query": { "match": { "title": "wind" } }, "highlight": { "require_field_match": false, "fields": { "synopsis": {} } } }'

現在 synopsis 也會被高亮——即使查詢沒直接匹配它,只要字段裡出現了 wind 這個詞就會被包標籤。

驗證命令:

curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hl/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{ "query": { "match": { "title": "wind" } }, "highlight": { "require_field_match": false, "fields": { "synopsis": {} } } }' \
  | grep -o '"synopsis"'

能 grep 到 "synopsis"(說明 synopsis 的高亮出現了)就通過。

第六步:組合——一個完整的高亮請求 + 收場

把前面的參數拼起來:搜 wind、高亮 title 和 synopsis 兩個字段、synopsis 裁成 2 段各 80 字符、用 <mark> 標籤:

curl -sk -u admin:Devfix@2026 -X GET "https://localhost:9200/movies_hl/_search?pretty" \
  -H "Content-Type: application/json" \
  -d '{
    "query": { "match": { "title": "wind" } },
    "highlight": {
      "pre_tags": [ "<mark>" ],
      "post_tags": [ "</mark>" ],
      "require_field_match": false,
      "fields": {
        "title":    {},
        "synopsis": { "fragment_size": 80, "number_of_fragments": 2 }
      }
    }
  }'

現在每個 hit 的 highlight 裡同時有 title(短文本整段高亮)和 synopsis(長文本裁成 2 段帶高亮),這正是搜索結果頁「標題高亮 + 簡介摘要」的完整形態。

收個尾:highlight 是純查詢期的行為,索引裡的數據一個字沒動,也無需 reindex——這點和改 mapping、改分析器不同。刪除演示索引即可收場:

curl -sk -u admin:Devfix@2026 -X DELETE "https://localhost:9200/movies_hl?pretty"
{
  "acknowledged" : true
}

核心概念

這張圖把 highlight 的參數和返回結構的關係擺清楚:請求裡 highlight 是頂層塊,fields 列出要高亮的字段,fragment_size/number_of_fragments 控片段、pre_tags/post_tags 控標籤、require_field_match 控是否跨字段;返回裡每個 hit 多一個 highlight 物件(字段名 → 片段陣列),原始 _source 不動。

OpenSearch 高亮鉛筆手繪詳解圖:左側定義卡解釋什麼是 highlight,中間橫排卡片對應正文六步,底部詳解 fragment_size、number_of_fragments、require_field_match 三個參數

參數 作用 預設值 類比
highlight 搜索請求頂層塊,聲明要高亮的字段 無(不傳不高亮) 熒光筆的開關
fragment_size 每個片段的字符數 100 每行摘要留多長
number_of_fragments 返回幾條片段;0 = 整個字段 5 摘要最多顯示幾行
pre_tags / post_tags 高亮標籤(陣列) <em> / </em> 用什麼筆色劃
require_field_match 是否只高亮查詢匹配的字段 true 只在查到的字段上劃,還是全篇找詞劃
type 高亮器:unified / plain / fvh / semantic unified 按句子切還是按長度硬切

要點回顧

  • highlight 不改數據,結果在 hits[].highlight——字段名 → 片段陣列,原始 _source 原樣保留,前端渲染讀 highlight、存數據讀 _source。
  • fragment_size 是字符數、number_of_fragments 是片段條數——一個管長度、一個管數量,別搞反;number_of_fragments: 0 返回整個字段全文。
  • highlight 要和 query 平級——塞進 query 裡會被忽略,字段名也要和 mapping 完全一致。
  • require_field_match 預設 true——只高亮查詢實際匹配的字段,跨字段高亮要設 false。

常見問題

傳了 highlight,返回裡沒有 highlight 物件

現象:搜完看 hits[0],沒有 highlight 物件,或 highlight 裡沒有 <em>。

原因:highlight 要和 query 平級(塞進 query 裡會被忽略);字段名要和 mapping 一致;且 require_field_match 預設 true,只高亮查詢實際匹配的字段,你高亮了一個查詢沒碰到的字段。

相關文章:OpenSearch 高亮沒生效:返回裡沒有 highlight 物件

高亮片段長度和條數對不上

現象:設了 fragment_size 和 number_of_fragments,片段長度、條數和預期不符。

原因:fragment_size 是片段字符數、number_of_fragments 是片段條數,兩者語義不同;number_of_fragments: 0 是返回整個字段,不是 0 條片段。

相關文章:OpenSearch 高亮片段不對:fragment_size 和 number_of_fragments 語義搞反

高亮某個字段報錯或沒結果

現象:高亮 keyword 字段報錯或沒 highlight;或 fvh 高亮器報 term vector 相關錯誤。

原因:高亮只能作用在 text 字段——keyword 字段不分詞、沒有詞位置信息;fvh 高亮器還要求 term_vector: with_positions_offsets。

相關文章:OpenSearch 高亮字段報錯/無結果:keyword 字段不能高亮

下一步

高亮之前,先排得對

高亮解決「命中怎麼展示」,命中誰排前面是相關性的事。BM25 打分、explain 溯源、boost 調權,返回體字段一起看更完整。

從零跑通 OpenSearch 相關性排序

對稱篇:Meilisearch 高亮

同一個「高亮與結果展示」問題,Meilisearch 用搜索參數 attributesToHighlight + _formatted 副本,OpenSearch 用 highlight DSL + highlight 陣列。兩篇對照讀,看清兩個引擎的取捨。

從零跑通 Meilisearch 高亮與結果展示

高亮要搭配長文本的兄弟:同義詞與停用詞

高亮的是「分詞後的詞」,同義詞和停用詞直接決定哪些詞進索引、哪些被剔除——分析器配得好,高亮才高得準。

從零跑通 OpenSearch 同義詞與停用詞

卡在哪一步了?

從零跑通的過程中撞到報錯?把命令和輸出記下來,幫助下一個剛起步的人。

貢獻一條解法