StackTraces
Meilisearch从零跑通

从零跑通 Meilisearch 高亮与结果展示:6 步,外加 3 个容易卡住的地方

@debug_master2026-11-18适用 [email protected]

跟着这篇走完,你会把 Meilisearch 搜索结果「怎么展示」这件事一次配齐:用 attributesToHighlight 把命中词包上 <em>、用 attributesToCrop 加 cropLength 把长文本裁成带省略号的摘录、用 showMatchesPosition 拿到匹配词的位置,最后用 attributesToRetrieve 只取需要的字段。整个过程 6 步,每步一条验证命令。环境沿用从零跑通 Meilisearch 本地搜索服务:localhost:7700、master key aSampleMasterKey、索引 movies(官方 movies.json 三万条电影);你换了值替换掉就行。

先说清一个贯穿整篇的认知:这些参数不改你的数据。高亮、裁剪的结果不是写回索引,而是引擎在返回体里额外放一个 _formatted 对象,原始字段(title、overview)原样保留。前端渲染高亮读 _formatted,存数据读原始字段,两处各司其职。这篇默认你已经跑通了本地搜索服务,建索引、异步任务轮询、POST /search 的写法全部复用,不再重复。

从零跑通 Meilisearch 高亮与结果展示 6 步流程封面:基线搜索 → 高亮 → 裁剪 → 自定义标签 → 匹配位置 → 收字段

前置条件

项 要求 说明
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(匹配位置),原始字段始终不动。

Meilisearch 高亮与结果展示铅笔手绘详解图:左侧定义卡解释什么是 _formatted,中间横排卡片对应正文六步,底部详解搜索参数如何加工返回字段

参数 作用 默认值 类比
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 编码也会静默失效。

相关文章:Meilisearch 高亮没生效:返回里没有 _formatted

裁剪出来的长度和预期差很多

现象:设了 cropLength: 10,以为拿到 10 个字符的摘要,结果英文片段明显更长;或短文本也被加了省略号。

原因:cropLength 的单位是词(words)不是字符,10 个英文词可能是 40+ 字符;且 cropMarker 只在真正发生裁剪时才插入,文本没超过长度就不裁、不加 …。

相关文章:Meilisearch 裁剪长度不对:cropLength 是词数不是字符

用 _matchesPosition 定位,字符串截出来是错的

现象:开了 showMatchesPosition 拿 start/length 去截字符串,高亮的位置总是错位,中文场景尤其明显。

原因:_matchesPosition 的 start/length 是字节偏移,不是字符下标。UTF-8 中文一个字符 3 字节,字节偏移和字符下标差 3 倍,直接 slice 必然错位。

相关文章:Meilisearch _matchesPosition 位置对不上:字节偏移不是字符下标

下一步

展示之前,先排得对

高亮、裁剪解决「命中怎么展示」,命中谁排前面是相关性的事。排序规则链和 _rankingScore 一起看,返回体字段更完整。

从零跑通 Meilisearch 排名规则与相关度评分

展示要搭配过滤分面

搜索结果页通常不是光秃秃的命中列表——左侧还有分类筛选、价格区间。filter 和 facets 是它的另一半。

从零跑通 Meilisearch 分面与过滤

同构的 OpenSearch 高亮

如果你技术栈在 OpenSearch 一侧,同一个「高亮与结果展示」问题它用 highlight 参数解决,机制不同(它改在查询 DSL 里)。对照着读能看清两个引擎的取舍。

从零跑通 OpenSearch:Docker 单节点起步

卡在哪一步了?

从零跑通的过程中撞到报错?把命令和输出记下来,帮助下一个刚起步的人。

贡献一条解法