以下是 Elasticsearch 主要查詢類型的示例及說明:
一、全文檢索查詢
-
Match Query
搜索分詞后的文本字段(如text
類型):GET /products/_search { "query": { "match": { "description": "wireless headphones" } } }
- 自動對
"wireless headphones"
分詞(如拆為wireless
和headphones
),匹配任一詞匯的文檔。
- 自動對
-
Multi-match Query
跨多個字段搜索:{ "query": { "multi_match": { "query": "apple", "fields": ["title", "brand", "description"] } } }
二、精確查詢
-
Term Query
精確匹配未分詞的keyword
字段:{ "query": { "term": { "status": { "value": "published" // 精確匹配字段值 } } } }
-
Terms Query
匹配字段中包含任一指定值的文檔:{ "query": { "terms": { "tags": ["electronics", "sale"] // 匹配含 electronics 或 sale 的文檔 } } }
-
Range Query
數值或日期范圍過濾:{ "query": { "range": { "price": { "gte": 100, "lte": 1000 } } } }
-
Exists Query
篩選存在某字段的文檔:{ "query": { "exists": { "field": "author" // 返回包含 author 字段的文檔 } } }
三、復合查詢
-
Bool Query 組合邏輯條件(AND/OR/NOT):
{ "query": { "bool": { "must": [ // 必須滿足 { "match": { "title": "phone" } }, { "range": { "price": { "lte": 500 } } } ], "must_not": [ // 必須不滿足 { "term": { "brand": "A" } } ], "should": [ // 滿足任意一個 { "term": { "color": "black" } }, { "term": { "color": "silver" } } ], "minimum_should_match": 1, // 至少滿足 1 個 should 條件 "filter": [ // 過濾,不參與評分 { "term": { "in_stock": true } } ] } } }
四、特殊查詢
-
Match_all Query
匹配所有文檔:{ "query": { "match_all": {} } }
-
Wildcard Query
通配符匹配(*
匹配任意字符,?
匹配單個字符):{ "query": { "wildcard": { "sku": "pro-*" // 匹配 pro-123, pro-abc 等 } } }
-
Prefix Query
前綴匹配:{ "query": { "prefix": { "city": "new" // 匹配 new york, new delhi 等 } } }
-
Fuzzy Query
容錯匹配(允許拼寫錯誤):{ "query": { "fuzzy": { "text": { "value": "quick", "fuzziness": "AUTO" // 自動允許 1-2 個字符的差異 } } } }
五、其他功能示例
-
分頁與排序
{ "query": { "match_all": {} }, "from": 10, // 跳過前 10 條 "size": 5, // 返回 5 條結果 "sort": [ { "price": { "order": "desc" } } // 按價格降序排序 ] }
-
高亮匹配內容
{ "query": { "match": { "content": "Elasticsearch" } }, "highlight": { "fields": { "content": {} // 高亮 content 字段中的匹配詞 } } }
關鍵注意事項
- 默認返回 10 條數據:在未顯式設置 size 參數時,Elasticsearch 的 search 查詢默認僅返回匹配結果的前 10 條記錄。
-
字段類型:
term
適用于keyword
類型,match
適用于text
類型。 -
性能:優先用
filter
替代must
進行精確過濾(如狀態、時間范圍),減少評分計算。