Distinct 属性
Distinct 属性是一个特殊的、用户指定的字段。它最常用于防止 Meilisearch 返回一组相似的文档,而是强制它只返回一个文档。
您可以通过两种方式设置 Distinct 属性:在配置期间使用 distinctAttribute
索引设置,或在搜索时使用 distinct
搜索参数。
在配置期间设置 Distinct 属性
distinctAttribute
是一种索引设置,用于配置 Meilisearch 应用于该索引中所有搜索和小平面检索的默认 Distinct 属性。
警告
每个索引只能有一个 distinctAttribute
。尝试将多个字段设置为 distinctAttribute
将返回错误。
配置为 Distinct 属性的字段的值在返回的文档中始终是唯一的。这意味着在返回的文档中,Distinct 属性字段中永远不会出现相同值的多次出现。
当多个文档对于 Distinct 属性具有相同的值时,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
将返回所有三个文档。这可能不是期望的结果,因为显示几乎相同的相同商品变体可能会使结果显得杂乱。
在这种情况下,您可能只想返回一个 product_id
与此 Lee 牛仔皮夹克对应的文档。为此,您可以将 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
是您可以添加到任何搜索查询的搜索参数。它允许您根据上下文选择性地使用 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"
}'