在 Meilisearch 中,facet(分面)是一种特殊类型的过滤器。本指南将展示如何配置 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 搜索参数:
curl \
-X POST 'MEILISEARCH_URL/indexes/books/search' \
-H 'Content-Type: application/json' \
--data-binary '{
"q": "classic",
"facets": [
"genres", "rating", "language"
]
}'
响应会返回所有匹配查询的书籍,同时包含两个可用于创建分面搜索界面的字段: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 列出了搜索结果中存在的所有分面,以及每个分面对应的文档数量。
facetStats 包含所有数值类型分面的最高值和最低值。
分面值排序
默认情况下,所有分面值都按字母数字升序排列。您可以通过 faceting 索引设置 中的 sortFacetValuesBy 属性来修改此行为:
curl \
-X PATCH 'MEILISEARCH_URL/indexes/books/settings/faceting' \
-H 'Content-Type: application/json' \
--data-binary '{
"sortFacetValuesBy": {
"genres": "count"
}
}'
上述代码示例将 genres 分面按值计数降序排序。
使用新设置重复之前的查询,会在 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
},
…
}
}
搜索分面值
您还可以通过 分面搜索端点 来搜索分面值:
curl \
-X POST 'MEILISEARCH_URL/indexes/books/facet-search' \
-H 'Content-Type: application/json' \
--data-binary '{
"facetQuery": "c",
"facetName": "genres"
}'
以下代码示例搜索 genres 分面中以 c 开头的值:
响应结果包含一个 facetHits 数组,列出所有匹配的分面及其对应的文档总数:
{
…
"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 参考中了解更多相关信息。