Meilisearch 提供了两条用于执行搜索的路由

  • POST 路由:当使用 API 认证时,这是首选路由,因为它允许 预检请求 缓存并提供更好的性能
  • GET 路由:不建议使用此路由,除非您有充分的理由(例如,特定的缓存能力)

您可以在本文末尾找到这两种路由接受的参数的详尽描述。

使用 POST 在索引中搜索

POST
/indexes/{index_uid}/search

在给定索引中搜索与特定查询匹配的文档。

当需要 API 密钥时,这是执行搜索的首选端点,因为它允许缓存预检请求。缓存预检请求**显著提高了搜索速度**。

默认情况下,此端点最多返回 1000 个结果。如果您想抓取数据库,请改用获取文档端点

路径参数

名称类型描述
index_uid *字符串请求索引的 uid

请求体

搜索参数类型默认值描述
q字符串""查询字符串
offset整数0要跳过的文档数量
limit整数20返回的最大文档数量
hitsPerPage整数1每页返回的最大文档数量
page整数1请求特定结果页
filter字符串或字符串数组null根据属性值筛选查询
facets字符串数组null显示每个分面的匹配计数
distinct字符串null将搜索限制为具有指定属性唯一值的文档
attributesToRetrieve字符串数组["*"]返回文档中要显示的属性
attributesToCrop字符串数组null值需要被截断的属性
cropLength整数10截断值(按词数)的最大长度
cropMarker字符串"..."标记截断边界的字符串
attributesToHighlight字符串数组null高亮显示属性中包含的匹配词条
highlightPreTag字符串"<em>"插入到高亮词条开头的字符串
highlightPostTag字符串"</em>"插入到高亮词条末尾的字符串
showMatchesPosition布尔值false返回匹配词条的位置
sort字符串数组null根据属性值对搜索结果进行排序
matchingStrategy字符串last用于匹配文档中查询词条的策略
showRankingScore布尔值false显示文档的全局排名分数
showRankingScoreDetails布尔值false添加详细的全局排名分数字段
rankingScoreThreshold数字null排除排名分数较低的结果
attributesToSearchOn字符串数组["*"]将搜索限制为指定的属性
hybrid对象null根据查询关键词和含义返回结果
vector数字数组null使用自定义查询向量进行搜索
retrieveVectors布尔值false返回文档向量数据
locales字符串数组null明确指定查询中使用的语言

响应

名称类型描述
hits对象数组查询结果
offset数字跳过的文档数量
limit数字要获取的文档数量
estimatedTotalHits数字估计的总匹配数量
totalHits数字详尽的总匹配数量
totalPages数字详尽的总搜索结果页数
hitsPerPage数字每页结果数量
page数字当前搜索结果页
facetDistribution对象给定分面的分布
facetStats对象每个分面的数值型 minmax
processingTimeMs数字查询的处理时间
query字符串产生响应的查询

详尽和估计的总搜索结果数量

默认情况下,Meilisearch 只返回查询结果总数的估计值:estimatedTotalHits。这是因为 Meilisearch 优先考虑相关性和性能,而不是提供详尽的搜索结果数量。在使用 estimatedTotalHits 时,请使用 offsetlimit 在搜索结果之间导航。

如果您需要搜索结果的总数,请在查询中使用 hitsPerPagepage 搜索参数。此查询的响应会将 estimatedTotalHits 替换为 totalHits,并包含一个额外字段 totalPages,其中包含根据您的 hitsPerPage 计算的搜索结果页数。使用 totalHitstotalPages 可能会导致性能略有下降,但在创建诸如带编号的页面选择器等 UI 元素时建议使用。

estimatedTotalHitstotalHits 都不能超过索引设置中 maxTotalHits 配置的限制。

您可以在我们的专用指南中阅读有关分页的更多信息

示例

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{ "q": "american ninja" }'

响应:200 Ok

{
  "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",
      "poster": "https://image.tmdb.org/t/p/w1280/svPHnYE7N5NAGO49dBmRhq0vDQ3.jpg",
      "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
    },

  ],
  "offset": 0,
  "limit": 20,
  "estimatedTotalHits": 976,
  "processingTimeMs": 35,
  "query": "american "
}

使用 GET 在索引中搜索

GET
/indexes/{index_uid}/search

在给定索引中搜索与特定查询匹配的文档。

此端点只接受字符串筛选表达式

此端点只应在不需要 API 密钥时使用。如果需要 API 密钥,请改用 POST 路由。

默认情况下,此端点最多返回 1000 个结果。如果您想抓取数据库,请改用获取文档端点

路径参数

名称类型描述
index_uid *字符串请求索引的 uid

查询参数

搜索参数类型默认值描述
q字符串""查询字符串
offset整数0要跳过的文档数量
limit整数20返回的最大文档数量
hitsPerPage整数1每页返回的最大文档数量
page整数1请求特定结果页
filter字符串或字符串数组null根据属性值筛选查询
facets字符串数组null显示每个分面的匹配计数
distinct字符串null将搜索限制为具有指定属性唯一值的文档
attributesToRetrieve字符串数组["*"]返回文档中要显示的属性
attributesToCrop字符串数组null值需要被截断的属性
cropLength整数10截断值(按词数)的最大长度
cropMarker字符串"..."标记截断边界的字符串
attributesToHighlight字符串数组null高亮显示属性中包含的匹配词条
highlightPreTag字符串"<em>"插入到高亮词条开头的字符串
highlightPostTag字符串"</em>"插入到高亮词条末尾的字符串
showMatchesPosition布尔值false返回匹配词条的位置
sort字符串数组null根据属性值对搜索结果进行排序
matchingStrategy字符串last用于匹配文档中查询词条的策略
showRankingScore布尔值false显示文档的全局排名分数
showRankingScoreDetails布尔值false添加详细的全局排名分数字段
rankingScoreThreshold数字null排除排名分数较低的结果
attributesToSearchOn字符串数组["*"]将搜索限制为指定的属性
hybrid对象null根据查询关键词和含义返回结果
vector数字数组null使用自定义查询向量进行搜索
retrieveVectors布尔值false返回文档向量数据
locales字符串数组null明确指定查询中使用的语言

响应

名称类型描述
hits对象数组查询结果
offset数字跳过的文档数量
limit数字要获取的文档数量
estimatedTotalHits数字估计的总匹配数量
totalHits数字详尽的总匹配数量
totalPages数字详尽的总搜索结果页数
hitsPerPage数字每页结果数量
page数字当前搜索结果页
facetDistribution对象给定分面的分布
facetStats对象每个分面的数值型 minmax
processingTimeMs数字查询的处理时间
query字符串产生响应的查询

示例

curl \
  -X GET 'MEILISEARCH_URL/indexes/movies/search?q=american%20ninja'

响应:200 Ok

{
  "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",
      "poster": "https://image.tmdb.org/t/p/w1280/svPHnYE7N5NAGO49dBmRhq0vDQ3.jpg",
      "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
    },

  ],
  "offset": 0,
  "limit": 20,
  "estimatedTotalHits": 976,
  "processingTimeMs": 35,
  "query": "american "
}

搜索参数

以下详尽描述了在使用搜索端点时当前可用的每个搜索参数。除非另有说明,所有参数对 GET /indexes/{index_uid}/searchPOST /indexes/{index_uid}/search/multi-search 路由均有效。

如果使用 GET 路由执行搜索,所有参数都必须进行URL 编码

使用 POST 路由或我们的某个 SDK 时,这没有必要。

查询 (q)

参数q
期望值:任何字符串
默认值null

设置搜索词条。

Meilisearch 只考虑任何给定搜索查询的前十个词。这是为了提供快速的即时搜索体验

示例

您可以通过设置 q 参数来搜索提及 shifu 的电影

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{ "q": "shifu" }'

这将为您提供一个包含您的查询词条的文档列表,其中查询词条至少存在于一个属性中。

{
  "hits": [
    {
      "id": 50393,
      "title": "Kung Fu Panda Holiday",
      "poster": "https://image.tmdb.org/t/p/w500/rV77WxY35LuYLOuQvBeD1nyWMuI.jpg",
      "overview": "The Winter Feast is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year Shifu informs Po that as Dragon Warrior, it is his duty to host the formal Winter Feast at the Jade Palace.",
      "release_date": 1290729600,
      "genres": [
        "Animation",
        "Family",
        "TV Movie"
      ]
    }
  ],
  "query": "shifu"
}

查询词条规范化

查询词条会经过一个规范化过程,该过程会移除非间距标记。因此,Meilisearch 在返回结果时会有效忽略重音和变音符号。例如,搜索 "sábia" 会返回包含 "sábia""sabiá""sabia" 的文档。

规范化还会将所有字母转换为小写。搜索 "Video" 返回的结果与搜索 "video""VIDEO""viDEO" 的结果相同。

当未指定 q 时,Meilisearch 会执行占位符搜索。占位符搜索会返回索引中所有可搜索的文档,并根据使用的任何搜索参数进行修改,以及根据该索引的自定义排名规则进行排序。由于没有查询词条,内置排名规则**不适用。**

如果索引没有排序或自定义排名规则,结果将按照其内部数据库位置的顺序返回。

占位符搜索在构建分面搜索界面时特别有用,因为它允许用户在不输入查询的情况下查看目录和更改排序规则。

如果您用双引号 (") 将搜索词条括起来,Meilisearch 将只返回包含这些词条且顺序与给定顺序相同的文档。这被称为短语搜索

短语搜索不区分大小写,并忽略软分隔符,例如 -,:。在短语搜索中使用硬分隔符会有效地将其拆分为多个独立的短语搜索:"Octavia.Butler" 将返回与 "Octavia" "Butler" 相同的结果。

您可以在单个搜索请求中结合短语搜索和普通查询。在这种情况下,Meilisearch 将首先获取与给定短语完全匹配的所有文档,然后按照其默认行为进行处理

示例
curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
--data-binary '{ "q": "\"african american\" horror" }'

在单词或短语前面使用减号 (-) 运算符,将其从搜索结果中排除。

示例

以下查询返回所有不包含单词“escape”的文档

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{ "q": "-escape" }'

排除搜索可以与短语搜索一起使用

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{ "q": "-\"escape room\"" }'

偏移量

参数offset
期望值:任何正整数
默认值0

设置搜索结果的起始点,有效跳过给定数量的文档。

使用 offsetlimit 的查询只返回搜索结果总数的估计值。

您可以通过结合 offsetlimit 进行查询来分页搜索结果

offset 设置为大于索引的 maxTotalHits 的值将返回一个空数组。

示例

如果您想跳过查询中的第一个结果,请将 offset 设置为 1

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "shifu",
    "offset": 1
  }'

限制

参数limit
期望值:任何正整数或零
默认值20

设置单个查询返回的最大文档数量。

您可以通过结合 offsetlimit 进行查询来分页搜索结果

搜索查询返回的结果不能超过maxTotalHits中配置的限制,即使 limit 的值大于 maxTotalHits 的值。

示例

如果您希望查询只返回两个文档,请将 limit 设置为 2

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "shifu",
    "limit": 2
  }'

每页结果数

参数hitsPerPage
期望值:任何正整数
默认值20

设置单个查询返回的最大文档数量。此参数配置的值决定总页数:如果 Meilisearch 找到总共 20 个匹配结果,并且您的 hitsPerPage 设置为 5,则 totalPages4

包含 hitsPerPage 的查询是详尽的,不会返回 estimatedTotalHits。相反,响应体将包含 totalHitstotalPages

如果您将 hitsPerPage 设置为 0,Meilisearch 将处理您的请求,但不会返回任何文档。在这种情况下,响应体将包含 totalHits 的详尽值。响应体还将包含 totalPages,但其值将为 0

您可以使用 hitsPerPagepage分页搜索结果

hitsPerPagepage 优先于 offsetlimit。如果查询包含 hitsPerPagepage,则传递给 offsetlimit 的任何值都将被忽略。

hitsPerPagepage 是资源密集型选项,可能会对搜索性能产生负面影响。如果maxTotalHits 设置为高于其默认值,则特别可能出现这种情况。

示例

以下示例返回查询的前 15 个结果

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "",
    "hitsPerPage": 15
  }'

参数page
期望值:任何正整数
默认值1

请求特定结果页。页数使用 hitsPerPage 搜索参数计算。

包含 page 的查询是详尽的,不会返回 estimatedTotalHits。相反,响应体将包含两个新字段:totalHitstotalPages

如果您将 page 设置为 0,Meilisearch 将处理您的请求,但不会返回任何文档。在这种情况下,响应体将包含 facetDistributiontotalPagestotalHits 的详尽值。

您可以使用 hitsPerPagepage分页搜索结果

hitsPerPagepage 优先于 offsetlimit。如果查询包含 hitsPerPagepage,则传递给 offsetlimit 的任何值都将被忽略。

hitsPerPagepage 是资源密集型选项,可能会对搜索性能产生负面影响。如果maxTotalHits 设置为高于其默认值,则特别可能出现这种情况。

示例

以下示例返回搜索结果的第二页

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "",
    "page": 2
  }'

筛选

参数filter
期望值:以字符串或字符串数组形式编写的筛选表达式
默认值[]

使用筛选表达式来优化搜索结果。用作筛选条件的属性必须添加到filterableAttributes 列表中。

有关更多信息,请阅读我们关于如何使用筛选器和构建筛选表达式的指南

示例

您可以使用逻辑连接符以字符串语法编写筛选表达式

"(genres = horror OR genres = mystery) AND director = 'Jordan Peele'"

您可以将相同的筛选器写成数组形式

[["genres = horror", "genres = mystery"], "director = 'Jordan Peele'"]

然后您可以在搜索查询中使用该筛选器

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "thriller",
    "filter": [
      [
        "genres = Horror",
        "genres = Mystery"
      ],
      "director = \"Jordan Peele\""
    ]
  }'

使用 _geoRadius_geoBoundingBox 筛选结果

如果您的文档包含 _geo 数据,您可以使用 _geoRadius_geoBoundingBox 内置筛选规则根据地理位置筛选结果。

如果任何参数无效或缺失,Meilisearch 将返回一个invalid_search_filter 错误。

分面

参数facets
期望值attribute 数组或 ["*"]
默认值null 返回每个给定分面与当前搜索查询匹配的文档数量。此参数可以取两个值

  • 属性数组:facets=["attributeA", "attributeB", …]
  • 一个星号——这将返回 filterableAttributes 中所有分面的计数

默认情况下,facets 为每个分面字段最多返回 100 个分面值。您可以使用faceting 索引设置maxValuesPerFacet 属性更改此值。

当设置 facets 时,搜索结果对象包含 facetDistributionfacetStats 字段。

如果用于 facets 的属性未添加到 filterableAttributes 列表中,它将被忽略。

facetDistribution

facetDistribution 包含在给定分面值中分布的匹配文档数量。每个分面都表示为一个对象

{

 "facetDistribution": {
    "FACET_A": {
      "FACET_VALUE_X": 6,
      "FACET_VALUE_Y": 1,
    },
    "FACET_B": {
      "FACET_VALUE_Z": 3,
      "FACET_VALUE_W": 9,
    },
  },

}

facetDistribution 包含传递给 facets 参数的每个属性的对象。每个对象包含该属性的返回值以及具有该值的匹配文档计数。Meilisearch 不会返回空分面。

facetStats

facetStats 包含每个分面中所有文档的最低 (min) 和最高 (max) 数值。只考虑数值

{

"facetStats": {
  "rating": {
    "min": 2.5,
    "max": 4.7
    }
  }

}

如果匹配文档中没有一个分面具有数值,则该分面不包含在 facetStats 对象中。facetStats 会忽略字符串值,即使字符串包含数字。

示例

给定一个电影评分数据库,以下代码示例返回每个类型中 Batman 电影的数量以及最低和最高评分

curl \
  -X POST 'MEILISEARCH_URL/indexes/movie_ratings/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "Batman",
    "facets": ["genres", "rating"]
  }'

响应显示了 genresrating 的分面分布。由于 rating 是一个数值字段,您可以在 facetStats 中获得其最小值和最大值。

{

  "estimatedTotalHits": 22,
  "query": "Batman",
  "facetDistribution": {
    "genres": {
      "Action": 20,
      "Adventure": 7,

      "Thriller": 3
    },
    "rating": {
      "2": 1,

      "9.8": 1
    }
  },
  "facetStats": {
    "rating": {
      "min": 2.0,
      "max": 9.8
    }
  }
}

在分面搜索指南中了解更多关于分面分布的信息。

搜索时的去重属性

参数distinct
期望值filterableAttributes 列表中存在的 attribute
默认值null

filterableAttributes 列表中的一个属性定义为去重属性。去重属性表示在指定字段中具有相同值的文档是等效的,并且在搜索结果中只应返回最相关的文档。

此行为类似于distinctAttribute 索引设置,但可以在搜索时进行配置。distinctAttribute 作为默认的去重属性值,您可以使用 distinct 覆盖它。

示例

curl \
  -X POST 'MEILISEARCH_URL/indexes/INDEX_NAME/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "QUERY TERMS",
    "distinct": "ATTRIBUTE_A"
  }'

要检索的属性

参数attributesToRetrieve
期望值attribute 数组或 ["*"]
默认值["*"]

配置返回文档中将检索哪些属性。

如果未指定值,attributesToRetrieve 将使用displayedAttributes 列表,该列表默认包含文档中找到的所有属性。

如果一个属性已从 displayedAttributes 中移除,attributesToRetrieve 将静默忽略它,并且该字段不会出现在您的返回文档中。

示例

要只获取 overviewtitle 字段,请将 attributesToRetrieve 设置为 ["overview", "title"]

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "shifu",
    "attributesToRetrieve": [
      "overview",
      "title"
    ]
  }'

要裁剪的属性

参数attributesToCrop
期望值:属性数组或 ["*"]
默认值null

将返回结果中选定字段裁剪到由 cropLength 参数指示的长度。当设置 attributesToCrop 时,每个返回的文档都包含一个名为 _formatted 的额外字段。此对象包含选定属性的裁剪版本。

默认情况下,裁剪边界由省略号字符 () 标记。您可以使用 cropMarker 搜索参数更改此设置。

(可选)您可以为提供给 attributesToCrop 的任何属性指定自定义裁剪长度:attributesToCrop=["attributeNameA:5", "attributeNameB:9"]。如果配置,这些值优先于 cropLength

除了提供单个属性外,您还可以提供 ["*"] 作为通配符:attributesToCrop=["*"]。这会导致 _formatted 包含attributesToRetrieve 中所有属性的裁剪值。

裁剪算法

假设您有一个字段包含以下字符串:Donatello is a skilled and smart turtle. Leonardo is the most skilled turtle. Raphael is the strongest turtle.

Meilisearch 在裁剪时会尽量尊重句子边界。例如,如果您的搜索词条是 Leonardo 并且您的 cropLength 是 6,Meilisearch 将优先保持句子完整并返回:Leonardo is the most skilled turtle.

如果查询只包含一个搜索词条,Meilisearch 会围绕该词条的第一次出现进行裁剪。如果您搜索 turtle 并且您的 cropLength 是 7,Meilisearch 将返回该词的第一次出现:Donatello is a skilled and smart turtle.

如果查询包含多个搜索词条,Meilisearch 会将裁剪中心放在最大数量的唯一匹配项周围,优先考虑彼此更近且遵循原始查询顺序的词条。如果您搜索 skilled turtlecropLength 为 6,Meilisearch 将返回 Leonardo is the most skilled turtle

如果 Meilisearch 在字段中找不到任何查询词条,裁剪将从该字段的第一个词开始。如果您搜索 MichelangelocropLength 为 4,并且此字符串存在于另一个字段中,Meilisearch 将返回 Donatello is a skilled …

示例

如果您使用 shifu 作为搜索查询并将 cropLength 参数的值设置为 5

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "shifu",
    "attributesToCrop": ["overview"],
    "cropLength": 5
  }'

您将获得以下响应,其中裁剪后的文本在 _formatted 对象中

{
  "id": 50393,
  "title": "Kung Fu Panda Holiday",
  "poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
  "overview": "The Winter Feast is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year Shifu informs Po that as Dragon Warrior, it is his duty to host the formal Winter Feast at the Jade Palace. Po is caught between his obligations as the Dragon Warrior and his family traditions: between Shifu and Mr. Ping.",
  "release_date": 1290729600,
  "_formatted": {
    "id": 50393,
    "title": "Kung Fu Panda Holiday",
    "poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
    "overview": "…this year Shifu informs Po…",
    "release_date": 1290729600
  }
}

裁剪长度

参数cropLength
期望值:正整数
默认值10

在使用 attributesToCrop 时,配置裁剪值中出现的总词数。如果未配置 attributesToCropcropLength 对返回结果没有影响。

查询词条计入裁剪值长度。如果 cropLength 设置为 2,并且您搜索一个词条(例如,shifu),裁剪后的字段将总共包含两个词(例如,"…Shifu informs…")。

停用词也计入此数字。如果 cropLength 设置为 2,并且您搜索一个词条(例如,grinch),裁剪结果可能包含一个停用词(例如,"…the Grinch…")。

如果 attributesToCrop 使用 attributeName:number 语法为属性指定自定义裁剪长度,则该值优先于 cropLength

裁剪标记

参数cropMarker
期望值:字符串
默认值"…"

在使用 attributesToCrop 参数时,设置一个字符串来标记裁剪边界。裁剪标记将插入到裁剪的两侧。如果未配置 attributesToCropcropMarker 对返回的搜索结果没有影响。

如果 cropMarker 设置为 null 或空字符串,则返回结果中不包含任何标记。

裁剪标记只在内容被移除的地方添加。例如,如果裁剪文本包含字段值的第一个词,则裁剪标记不会添加到裁剪结果的开头。

示例

当搜索 shifu 时,您可以使用 cropMarker 更改默认的

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "shifu",
    "cropMarker": "[…]",
    "attributesToCrop": ["overview"]
  }'
{
  "id": 50393,
  "title": "Kung Fu Panda Holiday",
  "poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
  "overview": "The Winter Feast is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year Shifu informs Po that as Dragon Warrior, it is his duty to host the formal Winter Feast at the Jade Palace. Po is caught between his obligations as the Dragon Warrior and his family traditions: between Shifu and Mr. Ping.",
  "release_date": 1290729600,
  "_formatted": {
    "id": 50393,
    "title": "Kung Fu Panda Holiday",
    "poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
    "overview": "[…]But this year Shifu informs Po that as Dragon Warrior,[…]",
    "release_date": 1290729600
  }
}

要高亮的属性

参数attributesToHighlight
期望值:属性数组或 ["*"]
默认值null

高亮显示指定属性中匹配的查询词条。attributesToHighlight 只适用于以下类型的值:字符串、数字、数组、对象。

设置此参数时,返回的文档包含一个 _formatted 对象,其中包含高亮显示的词条。

除了属性列表外,您还可以使用 ["*"]attributesToHighlight=["*"]。在这种情况下,attributesToRetrieve 中存在的所有属性都将分配给 attributesToHighlight

默认情况下,高亮元素用 <em></em> 标签括起来。您可以使用 highlightPreTaghighlightPostTag 搜索参数更改此设置。

attributesToHighlight 还会高亮显示配置为同义词停用词的词条。

attributesToHighlight 将高亮显示添加到 attributesToHighlight 数组中的所有属性内的匹配项,即使这些属性未设置为searchableAttributes

示例

以下查询高亮显示 overview 属性中存在的匹配项

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "winter feast",
    "attributesToHighlight": ["overview"]
  }'

文本的高亮版本随后将出现在每个返回文档中包含的 _formatted 对象中

{
  "id": 50393,
  "title": "Kung Fu Panda Holiday",
  "poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
  "overview": "The Winter Feast is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year Shifu informs Po that as Dragon Warrior, it is his duty to host the formal Winter Feast at the Jade Palace. Po is caught between his obligations as the Dragon Warrior and his family traditions: between Shifu and Mr. Ping.",
  "release_date": 1290729600,
  "_formatted": {
    "id": 50393,
    "title": "Kung Fu Panda Holiday",
    "poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
    "overview": "The <em>Winter Feast</em> is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year Shifu informs Po that as Dragon Warrior, it is his duty to host the formal <em>Winter Feast</em> at the Jade Palace. Po is caught between his obligations as the Dragon Warrior and his family traditions: between Shifu and Mr. Ping.",
    "release_date": 1290729600
  }
}

高亮标签

参数highlightPreTaghighlightPostTag
期望值:字符串
默认值:分别为 "<em>""</em>"

highlightPreTaghighlightPostTag 分别配置要在由 attributesToHighlight 高亮显示的词之前和之后插入的字符串。如果未配置 attributesToHighlighthighlightPreTaghighlightPostTag 对返回的搜索结果没有影响。

可以使用 highlightPreTaghighlightPostTag 将词条括在任何文本字符串之间,而不仅仅是 HTML 标签:"<em>""<strong>""*""__" 都是同样支持的值。

如果 highlightPreTaghighlightPostTag 设置为 null 或空字符串,则在高亮词条的开头或结尾将分别不插入任何内容。

示例

以下查询将高亮匹配项用带有 class 属性的 <span> 标签括起来

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "winter feast",
    "attributesToHighlight": ["overview"],
    "highlightPreTag": "<span class=\"highlight\">",
    "highlightPostTag": "</span>"
  }'

您可以在 _formatted 属性中找到高亮显示的查询词条

{
  "id": 50393,
  "title": "Kung Fu Panda Holiday",
  "poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
  "overview": "The Winter Feast is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year Shifu informs Po that as Dragon Warrior, it is his duty to host the formal Winter Feast at the Jade Palace. Po is caught between his obligations as the Dragon Warrior and his family traditions: between Shifu and Mr. Ping.",
  "release_date": 1290729600,
  "_formatted": {
    "id": 50393,
    "title": "Kung Fu Panda Holiday",
    "poster": "https://image.tmdb.org/t/p/w1280/gp18R42TbSUlw9VnXFqyecm52lq.jpg",
    "overview": "The <span class=\"highlight\">Winter Feast</span> is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year Shifu informs Po that as Dragon Warrior, it is his duty to host the formal <span class=\"highlight\">Winter Feast</span> at the Jade Palace. Po is caught between his obligations as the Dragon Warrior and his family traditions: between Shifu and Mr. Ping.",
    "release_date": 1290729600
  }
}

尽管不一定需要同时使用 highlightPreTaghighlightPostTag,但请注意确保标签正确匹配。在上述示例中,不设置 highlightPostTag 将导致 HTML 格式错误:<span>Winter Feast</em>

显示匹配位置

参数showMatchesPosition
期望值truefalse
默认值false

在搜索响应中添加一个 _matchesPosition 对象,其中包含查询词条在所有字段中每次出现的位置。当您需要比我们内置高亮提供的更多控制时,这很有用。showMatchesPosition 只适用于字符串、数字以及字符串和数字的数组。

showMatchesPosition 返回所有属性中匹配查询词条的位置,即使这些属性未设置为searchableAttributes

字段中匹配词条的开头由 start 指示,其长度由 length 指示。

startlength 以字节而不是字符数来衡量。例如,ü 代表两个字节但一个字符。

示例

如果您将 showMatchesPosition 设置为 true 并搜索 winter feast

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "winter feast",
    "showMatchesPosition": true
  }'

您将获得以下响应,其中_matchesPosition 对象中包含匹配项的信息。请注意 Meilisearch 如何因为空格而分别搜索 winterfeast

{
  "id": 50393,
  "title": "Kung Fu Panda Holiday",
  "poster": "https://image.tmdb.org/t/p/w500/rV77WxY35LuYLOuQvBeD1nyWMuI.jpg",
  "overview": "The Winter Feast is Po's favorite holiday. Every year he and his father hang decorations, cook together, and serve noodle soup to the villagers. But this year Shifu informs Po that as Dragon Warrior, it is his duty to host the formal Winter Feast at the Jade Palace. Po is caught between his obligations as the Dragon Warrior and his family traditions: between Shifu and Mr. Ping.",
  "release_date": 1290729600,
  "_matchesPosition": {
    "overview": [
      {
        "start": 4,
        "length": 6
      },
      {
        "start": 11,
        "length": 5
      },
      {
        "start": 234,
        "length": 6
      },
      {
        "start": 241,
        "length": 5
      }
    ]
  }
}

排序

参数sort
期望值:以数组或逗号分隔字符串形式编写的属性列表
默认值null

在查询时根据指定属性和指示顺序对搜索结果进行排序。

列表中每个属性后面必须跟一个冒号 (:) 和首选排序顺序:升序 (asc) 或降序 (desc)。

属性顺序是重要的。列表中排在前面的属性将优先于排在后面的属性。

例如,sort="price:asc,author:desc 在排序结果时将优先考虑 price 而非 author

使用 POST 路由时,sort 期望一个字符串数组。

使用 GET 路由时,sort 期望列表为逗号分隔的字符串。

在我们的专用指南中阅读更多关于排序搜索结果的信息。

示例

您可以搜索按价格从低到高排序的科幻书籍

curl \
  -X POST 'MEILISEARCH_URL/indexes/books/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "science fiction",
    "sort": ["price:asc"]
  }'

使用 _geoPoint 排序结果

处理包含地理位置数据的文档时,您可以使用 _geoPoint 根据文档与特定地理位置的距离对结果进行排序。

_geoPoint 是一个排序函数,需要两个浮点数来指示位置的纬度和经度。您还必须指定排序应为升序 (asc) 还是降序 (desc)

curl \
  -X POST 'MEILISEARCH_URL/indexes/restaurants/search' \
  -H 'Content-type:application/json' \
  --data-binary '{ "sort": ["_geoPoint(48.8561446,2.2978204):asc"] }'

使用 _geoPoint 的查询将始终包含一个 geoDistance 字段,其中包含文档位置与 _geoPoint 之间的距离(以米为单位)

[
  {
    "id": 1,
    "name": "Nàpiz' Milano",
    "_geo": {
      "lat": 45.4777599,
      "lng": 9.1967508
    },
    "_geoDistance": 1532
  }
]

您可以在我们的专用指南中阅读更多关于基于位置的排序的信息。

匹配策略

参数matchingStrategy
期望值lastallfrequency
默认值last

定义用于匹配文档中查询词条的策略。

last

last 首先返回包含所有查询词条的文档。如果没有足够的包含所有查询词条的结果来满足请求的 limit,Meilisearch 将一次移除一个查询词条,从查询的末尾开始。

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "big fat liar",
    "matchingStrategy": "last"
  }'

根据上述代码示例,Meilisearch 将首先返回包含所有三个词的文档。如果结果不满足请求的 limit,它还将返回仅包含前两个词 big fat 的文档,然后是仅包含 big 的文档。

all

all 只返回包含所有查询词条的文档。即使没有足够的文档来满足请求的 limit,Meilisearch 也不会匹配更多文档。

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "big fat liar",
    "matchingStrategy": "all"
  }'

上述代码示例将只返回包含所有三个词的文档。

frequency

frequency 首先返回包含所有查询词条的文档。如果没有足够的包含所有查询词条的结果来满足请求的限制,Meilisearch 将一次移除一个查询词条,从数据集中最常出现的词开始。frequency 有效地给予在结果集中出现频率较低的词更大的权重。

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "white shirt",
    "matchingStrategy": "frequency"
  }'

在许多文档包含词条 "shirt" 的数据集中,上述代码示例将优先考虑包含 "white" 的文档。

排名分数

参数showRankingScore
期望值truefalse
默认值false

为每个文档添加一个全局排名分数字段 _rankingScore_rankingScore 是一个介于 0.01.0 之间的数值。_rankingScore 越高,文档越相关。

sort 排名规则不影响 _rankingScore。相反,文档顺序由它们排序所依据的字段值决定。

文档的排名分数不会因同一索引中其他文档的分数而改变。

例如,如果文档 A 对某个查询词条的分数为 0.5,则无论文档 B、C 或 D 的分数如何,此值都保持不变。

示例

以下代码示例在 movies 中搜索 dragon 时返回 _rankingScore

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "dragon",
    "showRankingScore": true
  }'
{
  "hits": [
    {
      "id": 31072,
      "title": "Dragon",
      "overview": "In a desperate attempt to save her kingdom…",

      "_rankingScore": 0.92
    },
    {
      "id": 70057,
      "title": "Dragon",
      "overview": "A sinful martial arts expert wants…",

      "_rankingScore": 0.91
    },

  ],

}

排名分数详情

参数showRankingScoreDetails
期望值truefalse
默认值false

为每个文档添加一个详细的全局排名分数字段 _rankingScoreDetails_rankingScoreDetails 是一个对象,包含每个活动排名规则的嵌套对象。

排名分数详情对象

每个排名规则在其自己的对象中详细说明其分数。字段因排名规则而异。

words
  • order:此排名规则应用的顺序
  • score:此规则的排名分数
  • matchingWords:文档中匹配查询的词数
  • maxMatchingWords:文档中可以匹配查询的最大词数
typo
  • order:此特定排名规则应用的顺序
  • score:此规则的排名分数
  • typoCount:纠正的错别字数量,以便文档匹配查询词条
  • maxTypoCount:接受的最大错别字数量
proximity
  • order:此排名规则应用的顺序
  • score:此规则的排名分数
attribute
  • order:此排名规则应用的顺序
  • score:此规则的排名分数
  • attributeRankingOrderScore:根据匹配属性的最大属性排名顺序计算的分数
  • queryWordDistanceScore:根据查询中词的位置与匹配属性中词的位置之间的距离计算的分数
exactness
  • order:此排名规则应用的顺序
  • score:此规则的排名分数
  • matchTypeexactMatchmatchesStartnoExactMatch 之一
    • exactMatch:文档包含一个属性,该属性匹配所有查询词条,且词条之间没有其他词,并按给定顺序排列
    • matchesStart:文档包含一个属性,其中所有查询词条的顺序与原始查询相同
    • noExactMatch:文档包含一个属性,其中至少有一个查询词条与原始查询匹配
  • matchingWords:当 matchTypenoExactMatch 时,属性中精确匹配的数量
  • maxMatchingWords:当 matchTypenoExactMatch 时,属性中精确匹配的最大数量
field_name:direction

sort 排名规则不会在分数详情对象中显示为单个字段。相反,每个已排序的属性都作为自己的字段出现,后跟一个冒号 (:) 和排序方向:attribute:direction

  • order:此排名规则应用的顺序
  • value:用于排序的字段值
_geoPoint(lat:lng):direction
  • order:此排名规则应用的顺序
  • value:用于排序的字段值
  • distance:与 _geoDistance 相同
vectorSort(target_vector)
  • order:此特定排名规则应用的顺序
  • value:用于排序文档的向量
  • similarity:目标向量和值向量之间的相似度分数。1.0 表示完美相似,0.0 表示完美不相似

示例

以下代码示例在 movies 中搜索 dragon 时返回 _rankingScoreDetail

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "dragon",
    "showRankingScoreDetails": true
  }'
{
  "hits": [
    {
      "id": 31072,
      "title": "Dragon",
      "overview": "In a desperate attempt to save her kingdom…",

      "_rankingScoreDetails": {
        "words": {
          "order": 0,
          "matchingWords": 4,
          "maxMatchingWords": 4,
          "score": 1.0
        },
        "typo": {
          "order": 2,
          "typoCount": 1,
          "maxTypoCount": 4,
          "score": 0.75
        },
        "name:asc": {
          "order": 1,
          "value": "Dragon"
        }
      }
    },

  ],

}

排名分数阈值

参数rankingScoreThreshold
期望值:介于 0.01.0 之间的数字
默认值null

排除低于指定排名分数的结果。

排除的结果不计入 estimatedTotalHitstotalHits 和分面分布。

出于性能原因,如果高于 rankingScoreThreshold 的文档数量大于 limit,Meilisearch 不会评估剩余文档的排名分数。排名低于阈值的结果不会立即从候选集中移除。在这种情况下,Meilisearch 可能会高估 estimatedTotalHitstotalHits 和分面分布的计数。

示例

以下查询只返回排名分数大于 0.2 的结果

curl \
-X POST 'MEILISEARCH_URL/indexes/INDEX_NAME/search' \
-H 'Content-Type: application/json' \
--data-binary '{
    "q": "badman",
    "rankingScoreThreshold": 0.2
}'

在搜索时自定义要搜索的属性

参数attributesToSearchOn
期望值:以数组形式编写的可搜索属性列表
默认值["*"]

配置查询以只在指定的属性中查找词条。

除了属性列表外,您还可以向 attributesToSearchOn 传递通配符值 (["*"]) 和 null。在这两种情况下,Meilisearch 都将在所有可搜索属性中查找匹配项。

传递给 attributesToSearchOn 的属性也必须存在于 searchableAttributes 列表中。

attributesToSearchOn 中属性的顺序不影响相关性。

示例

以下查询返回其 overview 包含 "adventure" 的文档

curl \
  -X POST 'MEILISEARCH_URL/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "q": "adventure",
    "attributesToSearchOn": ["overview"]
  }'

结果将不包括在其他字段(如 titlegenre)中包含 "adventure" 的文档,即使这些字段存在于 searchableAttributes 列表中。

参数hybrid
期望值:一个包含两个字段的对象:embeddersemanticRatio
默认值null

配置 Meilisearch 以根据查询的含义和上下文返回搜索结果。

hybrid 必须是一个对象。它接受两个字段:embeddersemanticRatio

embedder 必须是一个字符串,指示通过 /settings 端点配置的嵌入器。在执行 AI 驱动的搜索时,必须指定一个有效的嵌入器。

semanticRatio 必须是一个介于 0.01.0 之间的数字,表示关键词搜索结果和语义搜索结果之间的比例。0.0 导致 Meilisearch 只返回关键词结果。1.0 导致 Meilisearch 只返回基于含义的结果。默认为 0.5

示例

curl -X POST 'MEILISEARCH_URL/indexes/INDEX_NAME/search' \
  -H 'content-type: application/json' \
  --data-binary '{
    "q": "kitchen utensils",
    "hybrid": {
      "semanticRatio": 0.9,
      "embedder": "EMBEDDER_NAME"
    }
  }'

向量

参数vector
期望值:数字数组
默认值null

使用自定义向量执行搜索查询。必须是与自定义向量维度对应的数字数组。

当使用 userProvided 嵌入器执行搜索时,vector 是强制性的。您还可以使用 vector 覆盖嵌入器的自动向量生成。

vector 维度必须与嵌入器的维度匹配。

如果查询未指定 q,但同时包含 vectorhybrid.semanticRatio 大于 0,Meilisearch 将执行纯语义搜索。

如果 q 缺失且 semanticRatio 明确设置为 0,Meilisearch 将执行占位符搜索,不包含任何向量搜索结果。

示例

curl -X POST 'MEILISEARCH_URL/indexes/INDEX_NAME/search' \
  -H 'content-type: application/json' \
  --data-binary '{ 
    "vector": [0, 1, 2],
    "hybrid": {
      "embedder": "EMBEDDER_NAME"
    }
  }'

在响应中显示 _vectors

参数retrieveVectors
期望值truefalse
默认值false

返回包含搜索结果的文档嵌入数据。如果为 true,Meilisearch 将在每个文档的 _vectors 字段中显示向量数据。

示例

curl -X POST 'MEILISEARCH_URL/indexes/INDEX_NAME/search' \
  -H 'content-type: application/json' \
  --data-binary '{
    "q": "kitchen utensils",
    "retrieveVectors": true,
    "hybrid": {
      "embedder": "EMBEDDER_NAME"
    }
  }'
{
  "hits": [
    {
      "id": 0,
      "title": "DOCUMENT NAME",
      "_vectors": {
        "default": {
          "embeddings": [0.1, 0.2, 0.3],
          "regenerate": true
        }
      }

    },

  ],

}

查询区域设置

参数locales
期望值支持的 ISO-639 区域设置数组
默认值[]

默认情况下,Meilisearch 会自动检测查询的语言。使用此参数可以明确指定查询的语言。

如果 locales本地化属性索引设置不匹配,此参数优先。

localeslocalizedAttributes 具有相同的目标:当 Meilisearch 的语言自动检测未按预期工作时,明确指定搜索中使用的语言。

如果您认为 Meilisearch 因查询文本而检测到不正确的语言,请使用 locales 明确设置搜索语言。

如果您认为 Meilisearch 因文档而检测到不正确的语言,请使用 localizedAttributes 在索引级别明确设置文档语言。

为了完全控制 Meilisearch 在索引和搜索时检测语言的方式,请同时设置 localeslocalizedAttributes

示例

curl \
-X POST 'MEILISEARCH_URL/indexes/INDEX_NAME/search' \
-H 'Content-Type: application/json' \
--data-binary '{
  "q": "QUERY TEXT IN JAPANESE",
  "locales": ["jpn"]
}'
{
  "hits": [
    {
      "id": 0,
      "title": "DOCUMENT NAME",
      "overview_jp": "OVERVIEW TEXT IN JAPANESE"
    }

  ],

}