引言

DSL(Domain Specific Language)是ES的查询语言。本文讲解ES查询DSL的实战应用。

一、全文查询

1.1 match查询

1
2
3
4
5
6
7
8
GET /products/_search
{
"query": {
"match": {
"name": "iPhone 14"
}
}
}

1.2 match_phrase查询

1
2
3
4
5
6
7
8
GET /products/_search
{
"query": {
"match_phrase": {
"name": "iPhone 14"
}
}
}

1.3 multi_match查询

1
2
3
4
5
6
7
8
9
GET /products/_search
{
"query": {
"multi_match": {
"query": "iPhone",
"fields": ["name", "description"]
}
}
}

二、精确查询

2.1 term查询

1
2
3
4
5
6
7
8
GET /products/_search
{
"query": {
"term": {
"category": "手机"
}
}
}

2.2 range查询

1
2
3
4
5
6
7
8
9
10
11
GET /products/_search
{
"query": {
"range": {
"price": {
"gte": 5000,
"lte": 10000
}
}
}
}

三、复合查询

3.1 bool查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
GET /products/_search
{
"query": {
"bool": {
"must": [
{ "match": { "name": "iPhone" } }
],
"filter": [
{ "range": { "price": { "gte": 5000 } } }
],
"should": [
{ "term": { "brand": "Apple" } }
],
"must_not": [
{ "term": { "status": "下架" } }
]
}
}
}

四、聚合查询

4.1 指标聚合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
GET /products/_search
{
"size": 0,
"aggs": {
"avg_price": {
"avg": { "field": "price" }
},
"max_price": {
"max": { "field": "price" }
},
"min_price": {
"min": { "field": "price" }
}
}
}

4.2 桶聚合

1
2
3
4
5
6
7
8
9
GET /products/_search
{
"size": 0,
"aggs": {
"categories": {
"terms": { "field": "category" }
}
}
}

总结

ES查询DSL核心:

  1. 全文查询:match、match_phrase
  2. 精确查询:term、range
  3. 复合查询:bool
  4. 聚合查询:指标聚合、桶聚合

参考资料