Distinct attribute

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

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

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

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

示例

假设您有一个电子商务数据集。对于包含有关jacket的信息的索引,您可能有几个相同的项目,只有一些细微的变化,例如 color 或 size。

如下所示,这个数据集包含三个文档,它们代表了 Lee jeans 的不同版本。一件是brown的,一件是black的,最后一件是blue的。

[
  {
    "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 leather jacket的product_id 。为此,可以将product_id 设置为 distinctAttribute。

# cURL
curl
  -X POST 'http://localhost:7700/indexes/jackets/settings' \
  -H 'Content-Type: application/json' \
  --data-binary '{ "distinctAttribute": "product_id" }'
# JS
client.index('jackets').updateSettings({ distinctAttribute: 'product_id' })
# python
client.index('jackets').update_settings({'distinctAttribute': 'product_id'})
# php
$client->index('jackets')->updateDistinctAttribute('product_id');
# java
Settings settings = new Settings();
settings.setDistinctAttribute("product_id");
client.index("jackets").updateSettings(settings);
# ruby
client.index('jackets').update_distinct_attribute('product_id')
# go
client.Index("jackets").UpdateDistinctAttribute("product_id")
# rust
let progress: Progress = client.index("jackets").set_distinct_attribute("product_id").await.unwrap();
# swift
client.index("jackets").updateDistinctAttribute("product_id") { (result: Result<Task, Swift.Error>) in
    switch result {
    case .success(let task):
        print(task)
    case .failure(let error):
        print(error)
    }
}
# dart
await client
    .index('jackets')
    .updateSettings(IndexSettings(distinctAttribute: '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,
  "nbHits": 1,
  "exhaustiveNbHits": false,
  "processingTimeMs": 0,
  "query": "lee leather jacket"
}