篩選搜尋結果
在本指南中,您將看到如何在假設的電影資料庫中設定和使用 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 'https://127.0.0.1:7700/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 日之後發行的 Avengers
電影
curl \
-X POST 'https://127.0.0.1:7700/indexes/movie_ratings/search' \
-H 'Content-Type: application/json' \
--data-binary '{
"q": "Avengers",
"filter": "release_date > 795484800"
}'
使用點號表示法,根據文件的巢狀欄位篩選結果。以下查詢僅會傳回具有良好使用者評價的驚悚片
curl \
-X POST 'https://127.0.0.1:7700/indexes/movie_ratings/search' \
-H 'Content-Type: application/json' \
--data-binary '{
"q": "thriller",
"filter": "rating.users >= 90"
}'
您也可以結合多個條件。例如,您可以限制搜尋,使其僅包含由 Tim Burton
或 Christopher Nolan
執導的 Batman
電影
curl \
-X POST 'https://127.0.0.1:7700/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\")"
}'
在這裡,括號是強制性的:如果沒有括號,篩選器會傳回由 Tim Burton
執導且於 1995 年之後發行的電影,或任何由 Christopher Nolan
執導的電影,而沒有發行日期的限制。發生這種情況是因為 AND
的優先順序高於 OR
。
如果您只想要不是由 Tim Burton
執導的最近 Planet of the Apes
電影,您可以使用此篩選器
curl \
-X POST 'https://127.0.0.1:7700/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 = "Tim Burton"
將會包含 director
欄位中不包含 "Tim Burton"
的文件和沒有 director
欄位的文件。若要僅傳回具有 director
欄位的文件,請使用 EXISTS
運算子展開篩選器表達式
release_date > 1577884550 AND (NOT director = "Tim Burton" AND director EXISTS)
警告
同義詞不適用於篩選器。也就是說,如果您將 SF
和 San Francisco
設定為同義詞,則依 SF
和 San Francisco
篩選會顯示不同的結果。