Elasticsearch查询

Bool 查询结构

POST /products/_search { "query": { "bool": { "must": [ { "match": { "name": "笔记本" } } // 参与评分 ], "filter": [ { "term": { "status": "available" } }, // 不评分,会被缓存 { "range": { "price": { "gte": 3000, "lte": 10000 } } } ], "should": [ { "match": { "brand": "联想" } }, // 匹配则提高评分 { "match": { "tags": "游戏本" } } ], "minimum_should_match": 1, "must_not": [ { "term": { "discontinued": true } } ] } }, "sort": [{ "_score": "desc" }, { "price": "asc" }], "from": 0, "size": 20, "_source": ["name", "price", "brand"] }

常用查询类型

查询类型使用场景说明
match分析字段全文搜索分词后匹配,参与评分
match_phrase短语精确匹配词序固定
multi_match多字段搜索支持字段权重 ^2
term精确值匹配(keyword/id)不分词,推荐放 filter
range数值/日期范围gte/lte/gt/lt
exists字段存在检查排除 null/缺失
fuzzy容错匹配(拼写纠错)fuzziness: "AUTO"
nested嵌套对象内查询需要 nested 类型映射

聚合查询

POST /orders/_search { "size": 0, "aggs": { "by_status": { "terms": { "field": "status", "size": 10 } }, "monthly_revenue": { "date_histogram": { "field": "created_at", "calendar_interval": "month" }, "aggs": { "total": { "sum": { "field": "amount" } }, "avg": { "avg": { "field": "amount" } } } }, "price_stats": { "percentiles": { "field": "amount", "percents": [50, 95, 99] } } } }