使用 facets 搜索
在 Meilisearch 中,facets 是一种特殊的过滤器。本指南将向你展示如何配置 facets,以及在搜索图书数据库时如何使用它们。它还提供了关于如何获取的说明
要求
- 一个 Meilisearch 项目
- 一个命令行终端
配置 facet 索引设置
首先,使用这个 图书数据集创建一个新索引。此数据集中的文档具有以下字段
{
"id": 5,
"title": "Hard Times",
"genres": ["Classics","Fiction", "Victorian", "Literature"],
"publisher": "Penguin Classics",
"language": "English",
"author": "Charles Dickens",
"description": "Hard Times is a novel of social […] ",
"format": "Hardcover",
"rating": 3
}
接下来,将 genres
、language
和 rating
添加到 filterableAttributes
列表中
curl \
-X PUT 'MEILISEARCH_URL/indexes/books/settings/filterable-attributes' \
-H 'Content-Type: application/json' \
--data-binary '[
"genres", "rating", "language"
]'
你现在已经配置了你的索引以使用这些属性作为过滤器。
在搜索查询中使用 facets
进行搜索查询,设置 facets
搜索参数
curl \
-X POST 'MEILISEARCH_URL/indexes/books/search' \
-H 'Content-Type: application/json' \
--data-binary '{
"q": "classic",
"facets": [
"genres", "rating", "language"
]
}'
响应返回所有匹配查询的图书。它还会返回两个字段,你可以使用它们来创建一个 faceted 搜索界面,facetDistribution
和 facetStats
{
"hits": [
…
],
…
"facetDistribution": {
"genres": {
"Classics": 6,
…
},
"language": {
"English": 6,
"French": 1,
"Spanish": 1
},
"rating": {
"2.5": 1,
…
}
},
"facetStats": {
"rating": {
"min": 2.5,
"max": 4.7
}
}
}
facetDistribution
列出了搜索结果中存在的所有 facets,以及每个 facet 返回的文档数量。
facetStats
包含所有包含数值的 facets 的最高和最低值。
排序 facet 值
默认情况下,所有 facet 值都按升序字母数字顺序排序。你可以使用 faceting
索引设置的 sortFacetValuesBy
属性来更改此设置
curl \
-X PATCH 'MEILISEARCH_URL/indexes/books/settings/faceting' \
-H 'Content-Type: application/json' \
--data-binary '{
"sortFacetValuesBy": {
"genres": "count"
}
}'
上面的代码示例按降序值计数对 genres
facet 进行排序。
使用新设置重复之前的查询将在 facetsDistribution
中产生不同的顺序
{
…
"facetDistribution": {
"genres": {
"Fiction": 8,
"Literature": 7,
"Classics": 6,
"Novel": 2,
"Horror": 2,
"Fantasy": 2,
"Victorian": 2,
"Vampires": 1,
"Tragedy": 1,
"Satire": 1,
"Romance": 1,
"Historical Fiction": 1,
"Coming-of-Age": 1,
"Comedy": 1
},
…
}
}
搜索 facet 值
你还可以使用 facet 搜索端点搜索 facet 值
curl \
-X POST 'MEILISEARCH_URL/indexes/books/facet-search' \
-H 'Content-Type: application/json' \
--data-binary '{
"facetQuery": "c",
"facetName": "genres"
}'
以下代码示例在 genres
facet 中搜索以 c
开头的值
响应包含一个 facetHits
数组,其中列出了所有匹配的 facets,以及包含该 facet 的文档总数
{
…
"facetHits": [
{
"value": "Children's Literature",
"count": 1
},
{
"value": "Classics",
"count": 6
},
{
"value": "Comedy",
"count": 2
},
{
"value": "Coming-of-Age",
"count": 1
}
],
"facetQuery": "c",
…
}
你可以使用 q
、filter
和 matchingStrategy
参数进一步优化结果。 在 API 参考中了解更多关于它们的信息。