開了
showMatchesPosition拿_matchesPosition做自定義高亮,用start/length去截字符串卻總是錯位,中文場景尤其明顯。根因是_matchesPosition的start/length是字節偏移(byte offset),不是字符下標——UTF-8 裡一箇中文字符佔 3 字節,把字節偏移當字符下標用,必然截偏。
Issue & Env(案發現場與環境)
- 業務場景:不想用預設
<em>高亮,想自己按_matchesPosition定位匹配詞、套自定義樣式。拿到start: 9, length: 5後,用 JS 的str.slice(9, 14)截出來,高亮的詞是錯的。 - 環境:Meilisearch v1.54.3,curl 復現,中文索引
books_zh。 - 關鍵區分:位置單位是字節,不是字符,也不是 JS 的 UTF-16 碼元。
StackTrace(返回體現狀)
中文場景,showMatchesPosition: true 返回的 _matchesPosition:
{
"hits": [
{
"id": 3,
"title": "夏日冰事",
"_matchesPosition": {
"title": [ { "start": 6, "length": 3 } ]
}
}
]
}
查詢詞「冰」在「夏日冰事」裡的字節偏移是 6(「夏」「日」各佔 3 字節,共 6 字節),長度 3(「冰」佔 3 字節)。如果你拿 title.slice(6, 9) 按字符下標截,截到的根本不是「冰」。
Reproduce(復現程式碼)
# 开 showMatchesPosition
curl -X POST 'http://localhost:7700/indexes/books_zh/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "冰", "showMatchesPosition": true }'
判定標準:返回 _matchesPosition.title[0] 的 start/length 是字節偏移,不是字符下標。對中文文本,字節偏移 ≈ 字符下標 × 3。
Root Cause(根因分析)
start/length 是字節偏移,不是字符下標
官方文檔明確:_matchesPosition 報告匹配詞的字節偏移(start 和 length),並特別註明「Positions are measured in bytes, not characters」。UTF-8 是變長編碼,ASCII 字符 1 字節,中文、emoji 等多字節字符 2–4 字節,所以字節偏移和字符下標不相等。
三種「下標」容易混
- 字節偏移(Meilisearch 返回的):UTF-8 字節序列裡的位置。
- JS 字符串下標:UTF-16 碼元位置(中文一個字符是 1 個碼元,emoji 是 2 個)。
- Unicode 碼點:邏輯字符數。
三種單位對多字節文本都不一致,直接拿字節偏移當任一種字符下標用都會錯。
報告範圍覆蓋所有字段
_matchesPosition 報告所有字段(包括非 searchable 字段)的匹配位置,用它做高亮時要知道它和 _formatted 的高亮範圍可能不完全重合。
The Fix(解決方案)
方案一:別自己算,直接用 _formatted 的預設高亮
絕大多數場景用預設 <em> 高亮就夠了,不必自己按字節截:
curl -X POST 'http://localhost:7700/indexes/books_zh/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "冰", "attributesToHighlight": ["title"] }'
方案二:真要自己定位,先轉字節再截
把字符串按 UTF-8 編碼成字節陣列,用字節偏移定位,再解碼回字符串。以下用 Node 示例(Buffer 按 UTF-8 字節處理):
const buf = Buffer.from(title, 'utf8'); // 按 UTF-8 字节
const matched = buf.subarray(start, start + length).toString('utf8'); // 按字节截取
注意事項
showMatchesPosition預設false,要顯式開。- 位置按字節計,做前端高亮優先用
_formatted+ 預設<em>,避免自己換算。 - 完整用法見 從零跑通 Meilisearch 高亮與結果展示。
References(參考來源)
- Search — Meilisearch 官方文檔meilisearch-docs
- Search with POST — Meilisearch 官方文檔meilisearch-docs
