在 Meilisearch 中,分面是一种特殊类型的筛选器。本指南将向您展示如何配置分面以及如何在图书数据库中搜索时使用它们。它还提供了如何获取的说明
- 一个 Meilisearch 项目
- 一个命令行终端
首先,使用此图书数据集创建一个新索引。此数据集中的文档具有以下字段
{
"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
列表中
您现在已将索引配置为使用这些属性作为筛选器。
在搜索查询中使用分面
进行搜索查询,设置 facets
搜索参数
响应返回所有与查询匹配的图书。它还返回两个字段,您可以用于创建分面搜索界面,即 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
属性更改此设置
上述代码示例按降序值计数对 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
},
…
}
}
搜索分面值
您还可以使用分面搜索端点搜索分面值
以下代码示例在 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 参考中了解更多信息。