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

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

在配置时设置去重属性

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

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

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

当多个文档的去重属性值相同时,Meilisearch 只会返回应用排序规则后排名最高的结果。如果两个或多个文档在排序上等价,Meilisearch 会根据其 internal_id 返回第一个结果。

示例

假设你有一个电子商务数据集。对于一个包含夹克衫信息的索引,可能会有多个几乎相同的商品,仅在颜色或尺寸等细节上存在差异。

如下所示,这个数据集包含三个文档,代表 Lee jeans 皮夹克的不同款式。其中一件是棕色,一件是黑色,最后一件是蓝色。

[
  {
    "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 jeans 皮夹克对应 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 的文档

如上设置 distinct 属性后,查询 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"
}

如需深入了解 distinct 属性,请查阅 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"
  }'