在 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` 列表中
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 参考中了解更多信息。
© . This site is unofficial and not affiliated with Meilisearch.