跟著這篇走完,你會把 Meilisearch 搜索結果「怎麼展示」這件事一次配齊:用 attributesToHighlight 把命中詞包上 <em>、用 attributesToCrop 加 cropLength 把長文本裁成帶省略號的摘錄、用 showMatchesPosition 拿到匹配詞的位置,最後用 attributesToRetrieve 只取需要的字段。整個過程 6 步,每步一條驗證命令。環境沿用從零跑通 Meilisearch 本地搜索服務:localhost:7700、master key aSampleMasterKey、索引 movies(官方 movies.json 三萬條電影);你換了值替換掉就行。
先說清一個貫穿整篇的認知:這些參數不改你的數據。高亮、裁剪的結果不是寫回索引,而是引擎在返回體裡額外放一個 _formatted 物件,原始字段(title、overview)原樣保留。前端渲染高亮讀 _formatted,存數據讀原始字段,兩處各司其職。這篇預設你已經跑通了本地搜索服務,建索引、異步任務輪詢、POST /search 的寫法全部複用,不再重複。

前置條件
| 項 | 要求 | 說明 |
|---|---|---|
| Meilisearch | v1.54 系,本地跑著 | 全文用 POST /search 調 REST API |
| 前置文章 | 已跑通 meilisearch-local-search | 複用其 movies 索引、master key、異步任務套路 |
| curl | 任意版本 | 全文用 curl |
先確認服務活著、movies 索引在:
curl 'http://localhost:7700/indexes/movies/stats' \
-H 'Authorization: Bearer aSampleMasterKey'
{
"numberOfDocuments": 31944,
"isIndexing": false,
"fieldDistribution": { "id": 31944, "title": 31944, "overview": 31944, "release_date": 31944 }
}
numberOfDocuments 三萬出頭、isIndexing: false 就滿足條件。報連接拒絕是服務沒起,回第一篇第一步;報 index_not_found 是索引沒建,回第一篇把 movies.json 導進去。
第一步:基線搜索——看原始返回長什麼樣
先不帶任何展示參數,搜一次 american,記住返回長什麼樣,後面每一步都和它對比:
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american" }'
{
"hits": [
{
"id": 2770,
"title": "American Pie 2",
"poster": "https://image.tmdb.org/t/p/w1280/q4LNgUnRfltxzp3gf1MAGiK5LhV.jpg",
"overview": "The whole gang are back and as close as ever. They decide to get even closer by spending the summer together at a beach house. They decide to hold the biggest...",
"release_date": 997405200
},
{
"id": 190859,
"title": "American Sniper",
"overview": "U.S. Navy SEAL Chris Kyle takes his sole mission—protect his comrades—to heart and becomes one of the most lethal snipers in American history. His pinpoint accuracy not only saves countless lives but also makes him a prime...",
"release_date": 1418256000
}
],
"estimatedTotalHits": 976,
"processingTimeMs": 3,
"query": "american"
}
三個觀察點,是後面的伏筆:① title 是原始值,命中詞 American 沒有高亮;② overview 是完整長文本,幾百個字符全塞在返回裡;③ 返回帶了 poster、release_date 等前端未必用得上的字段。這三件事,接下來四步分別解決。
驗證命令:
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american" }' | grep -o '"estimatedTotalHits":[0-9]*'
返回 "estimatedTotalHits":976 就通過(以本地實測為準,量級一致即可)。
第二步:attributesToHighlight 高亮命中詞(承重步)
這是全文承重的一步。搜索結果頁上「搜了什麼詞、哪段命中了」是用戶第一眼要看的,靠的就是 attributesToHighlight。加它,把要高的字段列進去:
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american", "attributesToHighlight": ["title"] }'
{
"hits": [
{
"id": 2770,
"title": "American Pie 2",
"overview": "The whole gang are back and as close as ever...",
"_formatted": {
"title": "<em>American</em> Pie 2"
}
},
{
"id": 190859,
"title": "American Sniper",
"_formatted": {
"title": "<em>American</em> Sniper"
}
}
]
}
注意看返回結構的變化,這是整篇的核心:
- 多了個
_formatted物件。高亮結果在這裡面,_formatted.title是<em>American</em> Pie 2。 - 原始
title沒動。hits[0].title還是American Pie 2,乾乾淨淨,不帶標籤。 - 命中詞被
<em>/</em>包住。這是預設標籤,第三步你也能換成別的。
所以前端渲染的時候,標題這一欄讀 hit._formatted.title,其它邏輯讀 hit.title——一個負責顯示、一個負責數據,互不汙染。這個「原始字段 + _formatted 副本」的設計,是 Meilisearch 和很多「直接改寫返回字段」的引擎不一樣的地方。
驗證命令:
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american", "attributesToHighlight": ["title"] }' \
| grep -o '<em>American</em>'
能 grep 到 <em>American</em> 就通過。
第三步:attributesToCrop + cropLength 裁剪長文本
overview 動輒幾百字,搜索界面只要一兩行摘要。裁剪靠兩個參數配合:attributesToCrop 指定裁哪個字段,cropLength 定最大詞數(是詞數,不是字符數,這是新手第一坑,見常見問題第 2 項):
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american", "attributesToCrop": ["overview"], "cropLength": 10 }'
{
"hits": [
{
"id": 190859,
"title": "American Sniper",
"overview": "U.S. Navy SEAL Chris Kyle takes his sole mission—protect his comrades—to heart...",
"_formatted": {
"overview": "…becomes one of the most lethal snipers in American history. His pinpoint accuracy…"
}
}
]
}
三個細節:
- 裁剪圍繞匹配詞居中。
American落在overview後半段,裁剪就把American放在片段中間,前後留上下文——這樣高亮和語境一起出現,用戶才知道「為什麼這條命中了」。 cropMarker預設"…",且只在真裁剪時出現。片段首尾的…表示「兩頭還有內容被裁掉了」。如果字段本身沒超過cropLength,就不會裁剪,也就沒有…。- 裁剪結果同樣在
_formatted裡,原始overview完整保留。
如果不同字段想要不同長度,用 "字段:词数" 語法按字段覆蓋:"attributesToCrop": ["overview:30", "title"]。
驗證命令:
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american", "attributesToCrop": ["overview"], "cropLength": 10 }' \
| grep -o '…[^…]*American[^…]*…'
能 grep 到「首尾帶 …、中間含 American」的片段就通過。
第四步:自定義高亮標籤 + 同義詞也會被高亮
預設 <em> 夠用,但如果你用的是 <mark>、或者想給高亮加 class,就換 highlightPreTag / highlightPostTag:
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american", "attributesToHighlight": ["title"], "highlightPreTag": "<mark class=\"hl\">", "highlightPostTag": "</mark>" }'
{
"hits": [
{
"id": 2770,
"title": "American Pie 2",
"_formatted": {
"title": "<mark class=\"hl\">American</mark> Pie 2"
}
}
]
}
<em> 換成了 <mark class="hl">。兩個標籤要成對換,只換一半會產出沒閉合的 HTML(見官方文檔對 highlightPostTag 的提醒)。
還有一個容易漏的點:高亮對同義詞和停用詞同樣生效。如果你配了同義詞,搜一個詞,被同義詞帶出來的命中也一樣會被高亮——高亮的是「匹配發生在哪」,不區分是原詞還是同義詞帶出來的。這是好事,用戶不需要關心機制,只需要看到「哪裡命中了」。
驗證命令:
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american", "attributesToHighlight": ["title"], "highlightPreTag": "<mark>", "highlightPostTag": "</mark>" }' \
| grep -o '<mark>American</mark>'
能 grep 到 <mark>American</mark> 就通過。
第五步:showMatchesPosition 拿匹配詞位置
預設高亮夠用,但如果你想自己控制高亮樣式(比如不整詞高亮、或做自定義渲染),就開 showMatchesPosition,拿到匹配詞在字段裡的位置:
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american", "showMatchesPosition": true }'
{
"hits": [
{
"id": 2770,
"title": "American Pie 2",
"_matchesPosition": {
"title": [ { "start": 0, "length": 8 } ],
"overview": [ { "start": 0, "length": 8 } ]
}
}
]
}
_matchesPosition.title 是一個陣列,每個元素一個匹配位置:start 是起始偏移、length 是匹配長度。start: 0, length: 8 對應 American 這 8 個字節。
這裡有一箇中文場景必踩的坑:start/length 是字節偏移,不是字符下標。 American 是純 ASCII,一個字符一字節,兩者恰好相等;但換成中文(UTF-8 一個漢字 3 字節),字節偏移就和字符下標差 3 倍。直接用字節偏移去 slice 字符串會錯位——見常見問題第 3 項。所以絕大多數場景,用第二步的預設高亮就好,別自己按位置截。
驗證命令:
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american", "showMatchesPosition": true }' \
| grep -o '_matchesPosition'
能 grep 到 _matchesPosition 就通過。
第六步:attributesToRetrieve 收字段 + 組合收場
第一步的返回帶了 poster、release_date 等字段,搜索結果頁可能只要 id、title、overview。attributesToRetrieve 指定只返回哪些字段(預設 ["*"] 全返):
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american", "attributesToRetrieve": ["id", "title", "overview"], "attributesToHighlight": ["title"], "attributesToCrop": ["overview"], "cropLength": 12 }'
{
"hits": [
{
"id": 2770,
"title": "American Pie 2",
"overview": "The whole gang are back and as close as ever...",
"_formatted": {
"title": "<em>American</em> Pie 2",
"overview": "…spending the summer together at a beach house. They decide to hold the biggest…"
}
}
]
}
現在一個返回體同時滿足:字段裁剪(只剩 id/title/overview)、高亮(_formatted.title 帶 <em>)、長文本截斷(_formatted.overview 帶 …)。這正是搜索界面拿到手就能直接渲染的樣子。
到這裡六個參數都過了一遍。收個尾:這套展示參數全是搜索請求裡的參數,索引裡的數據一個字沒動,也無需任何 reindex——這也是它和「改設置」類操作(如 filterableAttributes、synonyms)最大的區別:那些要等異步任務、改的是索引行為,這些只在單次查詢裡生效、即時返回。
核心概念
這張圖把六個搜索參數和返回體結構的關係擺清楚:請求裡的參數分兩組——attributesToRetrieve 決定「返回哪些字段」,attributesToHighlight / attributesToCrop / cropLength / showMatchesPosition 決定「這些字段怎麼加工」;加工結果進 _formatted(高亮/裁剪)和 _matchesPosition(匹配位置),原始字段始終不動。

| 參數 | 作用 | 預設值 | 類比 |
|---|---|---|---|
attributesToHighlight |
高亮命中詞,結果進 _formatted |
null |
熒光筆劃出命中的詞 |
attributesToCrop |
裁剪長文本,結果進 _formatted |
null |
把長段落截成一句話摘要 |
cropLength |
裁剪最大詞數(詞,不是字符) | 10 |
摘要最多留幾個詞 |
cropMarker |
裁剪邊界標記 | "…" |
省略號,提示「還有內容被裁掉」 |
showMatchesPosition |
返回匹配詞字節偏移 | false |
告訴你命中在字符串第幾個字節 |
attributesToRetrieve |
控制返回哪些字段 | ["*"] |
只把要的列投影出來 |
要點回顧
- 展示參數不改數據,加工結果進
_formatted——高亮、裁剪都在_formatted副本里,原始title/overview原樣保留,前端渲染讀_formatted、存數據讀原始字段。 cropLength是詞數不是字符數——英文按空格分詞、中文按分詞器切詞,把詞數當字符數設,長度必然對不上。cropMarker只在真裁剪時出現——字段沒超過cropLength就不裁、也不加…。_matchesPosition是字節偏移不是字符下標——中文 UTF-8 一字 3 字節,自己按位置截字符串必錯位,優先用預設<em>高亮。
常見問題
傳了 attributesToHighlight,返回裡沒有 _formatted
現象:搜完看 hits[0].title,還是純文本沒有 <em>,也沒找到 _formatted 物件。
原因:attributesToHighlight 是搜索參數不是索引設置,要每次請求都帶;且高亮結果只在 _formatted 裡、不在原始字段。參數名大小寫拼錯或走 GET 沒 URL 編碼也會靜默失效。
裁剪出來的長度和預期差很多
現象:設了 cropLength: 10,以為拿到 10 個字符的摘要,結果英文片段明顯更長;或短文本也被加了省略號。
原因:cropLength 的單位是詞(words)不是字符,10 個英文詞可能是 40+ 字符;且 cropMarker 只在真正發生裁剪時才插入,文本沒超過長度就不裁、不加 …。
用 _matchesPosition 定位,字符串截出來是錯的
現象:開了 showMatchesPosition 拿 start/length 去截字符串,高亮的位置總是錯位,中文場景尤其明顯。
原因:_matchesPosition 的 start/length 是字節偏移,不是字符下標。UTF-8 中文一個字符 3 字節,字節偏移和字符下標差 3 倍,直接 slice 必然錯位。
