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] }
}
}
}