去重属性是一个特殊的、用户指定的字段。它最常用于防止 Meilisearch 返回一组多个相似文档,而是强制它只返回一个文档。

您可以通过两种方式设置去重属性:在配置时使用 distinctAttribute 索引设置,或者在搜索时使用 distinct 搜索参数。

配置时设置去重属性

distinctAttribute 是一个索引设置,它配置 Meilisearch 应用于该索引中所有搜索和分面检索的默认去重属性。

每个索引只能有一个 distinctAttribute。尝试将多个字段设置为 distinctAttribute 将会返回错误。

配置为去重属性的字段值在返回的文档中始终是唯一的。这意味着在返回的文档中,去重属性字段的相同值永远不会出现多次

当多个文档具有相同的去重属性值时,Meilisearch 在应用排名规则后只返回排名最高的文档。如果两个或更多文档在排名方面相同,Meilisearch 将根据其 internal_id 返回第一个结果。

示例

假设您有一个电子商务数据集。对于包含夹克信息的索引,您可能有几个相同但存在颜色或尺寸等微小差异的商品。

如下所示,此数据集包含三个文档,分别代表 Lee 牛仔皮夹克的不同版本。其中一件夹克是棕色的,一件是黑色的,最后一件是蓝色的。

[
  {
    "id": 1,
    "description": "Leather jacket",
    "brand": "Lee jeans",
    "color": "brown",
    "product_id": "123456"
  },
  {
    "id": 2,
    "description": "Leather jacket",
    "brand": "Lee jeans",
    "color": "black",
    "product_id": "123456"
  },
  {
    "id": 3,
    "description": "Leather jacket",
    "brand": "Lee jeans",
    "color": "blue",
    "product_id": "123456"
  }
]

默认情况下,搜索 lee leather jacket 将返回所有三个文档。这可能不是理想的结果,因为显示几乎相同的商品变体可能会使结果显得杂乱。

在这种情况下,您可能只想返回一个与此 Lee 牛仔皮夹克对应的 product_id 的文档。为此,您可以将 product_id 设置为 distinctAttribute

curl \
  -X PUT 'MEILISEARCH_URL/indexes/jackets/settings/distinct-attribute' \
  -H 'Content-Type: application/json' \
  --data-binary '"product_id"'

通过将 distinctAttribute 设置为 product_id,搜索请求将永远不会返回多个具有相同 product_id 的文档

如上所示设置去重属性后,查询 lee leather jacket 将只返回找到的第一个文档。响应将如下所示:

{
  "hits": [
    {
      "id": 1,
      "description": "Leather jacket",
      "brand": "Lee jeans",
      "color": "brown",
      "product_id": "123456"
    }
  ],
  "offset": 0,
  "limit": 20,
  "estimatedTotalHits": 1,
  "processingTimeMs": 0,
  "query": "lee leather jacket"
}

有关去重属性的更多深入信息,请查阅API 参考

搜索时设置去重属性

distinct 是您可以添加到任何搜索查询的搜索参数。它允许您根据上下文选择性地使用去重属性。distinct 优先于 distinctAttribute

要将属性与 distinct 一起使用,请首先将其添加到 filterableAttributes 列表

curl \
  -X PUT 'MEILISEARCH_URL/indexes/products/settings/filterable-attributes' \
  -H 'Content-Type: application/json' \
  --data-binary '[
    "product_id",
    "sku",
    "url"
  ]'

然后,在搜索查询中使用 distinct,指定一个已配置的属性

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