去重属性是一个特殊的用户指定字段。它最常用于阻止 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"
  }'
© . This site is unofficial and not affiliated with Meilisearch.