設了
attributesToCrop和cropLength,裁出來的摘錄長度和預期差很多——比如以為cropLength: 10是 10 個字符,結果英文摘要遠比 10 個字符長。根因是cropLength的單位是詞(words)不是字符,英文按空格分詞算、中文按分詞器切詞算;且cropMarker只在真正發生裁剪時才插入,短文本不會加省略號。
Issue & Env(案發現場與環境)
- 業務場景:搜索界面要把長
overview截成短摘錄,設了attributesToCrop: ["overview"]和cropLength: 10,以為拿到 10 個字符左右的摘要,實際返回的英文片段明顯長得多,或者乾脆沒有…。 - 環境:Meilisearch v1.54.3,curl 復現,索引
movies。 - 關鍵區分:
cropLength是詞數上限,且裁剪會圍繞匹配詞居中;cropMarker只在確有內容被裁掉時插入。
StackTrace(返回體現狀)
cropLength: 10 對英文 overview 的實際效果——約 10 個詞、幾十個字符,首尾帶 …:
{
"hits": [
{
"id": 190859,
"overview": "U.S. Navy SEAL Chris Kyle takes his sole mission—protect his comrades—to heart...",
"_formatted": {
"overview": "…U.S. Navy SEAL Chris Kyle takes his sole mission—protect his comrades—to heart and becomes…"
}
}
]
}
… 出現在首尾(cropMarker 預設 "…"),中間是約 10 個詞的片段。如果你預期的是「10 個字符」,這裡會明顯超預期。
Reproduce(復現程式碼)
# 以为 cropLength 是字符,实际是词
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 }'
# 短文本不裁剪、不加 marker:把 cropLength 设很大,overview 完整返回、没有 …
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "shifu", "attributesToCrop": ["overview"], "cropLength": 1000 }'
判定標準:第一條返回 _formatted.overview 約 10 個詞、帶 …;第二條 cropLength 大到超過文本長度,_formatted.overview 等於原文、沒有 …。
Root Cause(根因分析)
cropLength 的單位是詞,不是字符
官方文檔明確 cropLength 是「Maximum number of words to include in cropped values」。英文一個「詞」由空格/標點切分,10 個詞可能是 40+ 個字符;中文按分詞器切詞,10 個「詞」也不是 10 個字。把詞數當字符數,長度必然對不上。
cropMarker 只在真正裁剪時插入
cropMarker(預設 "…")標記的是「內容被裁掉」的邊界。如果文本本身不超過 cropLength,沒有內容被裁,就不會出現 …。所以「短文本也帶省略號」的預期是錯的——那不是 bug,是沒觸發裁剪。
裁剪圍繞匹配詞居中,且支持按字段覆蓋
裁剪儘量讓匹配詞落在片段中間(好讓高亮和上下文一起出現)。不同字段想要不同長度,用 "attribute:length" 語法按字段覆蓋,例如 ["overview:30", "title"]。
The Fix(解決方案)
第一步:把 cropLength 當詞數來設
英文想要約 30 個字符的摘要,按平均一個詞 5 字符,cropLength 設 6 左右;要精確就多試幾次看實際效果。
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": 6 }'
第二步:按字段定製長度
curl -X POST 'http://localhost:7700/indexes/movies/search' \
-H 'Authorization: Bearer aSampleMasterKey' \
-H 'Content-Type: application/json' \
--data-binary '{ "q": "american", "attributesToCrop": ["overview:30", "title"], "cropLength": 10 }'
overview 裁到 30 詞,其餘字段用預設 cropLength。
注意事項
cropMarker只在確有裁剪時出現;想自定義標記改cropMarker。- 裁剪結果在
_formatted裡,原始字段不變。 - 查詢詞和停用詞都計入
cropLength。 - 完整用法見 從零跑通 Meilisearch 高亮與結果展示。
References(參考來源)
- Search — Meilisearch 官方文檔meilisearch-docs
- Search with POST — Meilisearch 官方文檔meilisearch-docs
