筛选搜索结果
在本指南中,您将了解如何在假设的电影数据库中配置和使用 Meilisearch 过滤器。
配置索引设置
假设您有一个名为 movie_ratings
的电影集合,其中包含以下字段
[
{
"id": 458723,
"title": "Us",
"director": "Jordan Peele",
"release_date": 1552521600,
"genres": [
"Thriller",
"Horror",
"Mystery"
],
"rating": {
"critics": 86,
"users": 73
},
},
…
]
如果您想根据属性过滤结果,您必须首先将其添加到 filterableAttributes
列表中
curl \
-X PUT 'MEILISEARCH_URL/indexes/movie_ratings/settings/filterable-attributes' \
-H 'Content-Type: application/json' \
--data-binary '[
"genres",
"director",
"release_date",
"ratings"
]'
此步骤是强制性的,不能在搜索时完成。 更新 filterableAttributes
需要 Meilisearch 重新索引所有数据,这将花费与数据集大小和复杂性成正比的时间。
注意
默认情况下,filterableAttributes
为空。 如果不首先将属性显式添加到 filterableAttributes
列表中,则过滤器不起作用。
搜索时使用 filter
更新 filterableAttributes
索引设置后,您可以使用 filter
来微调搜索结果。
filter
是您可以在搜索时使用的搜索参数。 filter
接受使用 filterableAttributes
列表中存在的任何属性构建的 过滤器表达式。
以下代码示例返回 1995 年 3 月 18 日之后上映的 复仇者联盟
电影
curl \
-X POST 'MEILISEARCH_URL/indexes/movie_ratings/search' \
-H 'Content-Type: application/json' \
--data-binary '{
"q": "Avengers",
"filter": "release_date > 795484800"
}'
使用点表示法根据文档的嵌套字段过滤结果。 以下查询仅返回用户评价良好的惊悚片
curl \
-X POST 'MEILISEARCH_URL/indexes/movie_ratings/search' \
-H 'Content-Type: application/json' \
--data-binary '{
"q": "thriller",
"filter": "rating.users >= 90"
}'
您还可以组合多个条件。 例如,您可以限制搜索,使其仅包含 蝙蝠侠
电影,导演为 蒂姆·伯顿
或 克里斯托弗·诺兰
curl \
-X POST 'MEILISEARCH_URL/indexes/movie_ratings/search' \
-H 'Content-Type: application/json' \
--data-binary '{
"q": "Batman",
"filter": "release_date > 795484800 AND (director = \"Tim Burton\" OR director = \"Christopher Nolan\")"
}'
在这里,括号是强制性的:没有它们,过滤器将返回由 蒂姆·伯顿
执导并在 1995 年之后发行的电影,或任何由 克里斯托弗·诺兰
执导的电影,而对其发行日期没有限制。 发生这种情况是因为 AND
优先于 OR
。
如果您只想查看最近的 人猿星球
电影,且导演不是 蒂姆·伯顿
,您可以使用此过滤器
curl \
-X POST 'MEILISEARCH_URL/indexes/movie_ratings/search' \
-H 'Content-Type: application/json' \
--data-binary '{
"q": "Planet of the Apes",
"filter": "release_date > 1577884550 AND (NOT director = \"Tim Burton\")"
}' \
NOT director = "蒂姆·伯顿"
将包括导演字段中不包含 "蒂姆·伯顿"
的文档和没有导演字段的文档。 要仅返回具有导演字段的文档,请使用 EXISTS
运算符扩展过滤器表达式
release_date > 1577884550 AND (NOT director = "Tim Burton" AND director EXISTS)
警告
同义词 不适用于过滤器。 也就是说,如果您将 SF
和 旧金山
设置为同义词,则按 SF
和 旧金山
过滤将显示不同的结果。