搜索是 Elasticsearch 的核心功能之一。本篇將介紹如何構建高效的查詢、優化搜索結果,以及調整相關性評分,幫助你充分發揮 Elasticsearch 的搜索能力。
1. 基礎查詢
1.1 Match Query 與 Term Query 的區別
-
Match Query:用于全文搜索,會對查詢詞進行分詞。
GET /my_index/_search {"query": {"match": {"title": "Elasticsearch 入門"}} }
- 匹配包含 “Elasticsearch” 或 “入門” 的文檔。
- 適用于
text
類型字段。
-
Term Query:用于精確匹配,不分詞。
GET /my_index/_search {"query": {"term": {"author.keyword": "text"}} }
- 僅匹配
author
精確為 “Text” 的文檔。 - 適用于
keyword
類型字段。
- 僅匹配
1.2 多條件查詢(Bool Query)
Bool Query
組合多個條件:
must
:必須滿足(AND)。should
:至少滿足一個(OR)。must_not
:必須不滿足(NOT)。filter
:過濾,不影響評分。
示例:
GET /my_index/_search
{"query": {"bool": {"must": { "match": { "title": "Elasticsearch" } },"filter": { "term": { "author.keyword": "Text" } },"must_not": { "range": { "date": { "lte": "2025-01-01" } } }}}
}
Mermaid 圖示 - Bool Query 邏輯