elasticsearch查询DSL

全部搜索

1
2
3
4
5
6
GET /index/type/_search
{
"query": {
"match_all": {}
}
}

例如:

1
2
3
4
5
6
GET /ecommerce/product/_search
{
"query": {
"match_all": {}
}
}

分页搜索

1
2
3
4
5
6
7
8
GET /index/type/_search
{
"query": {
xxx
},
"from": 0,
"size": 10
}

例如:

1
2
3
4
5
6
7
8
GET /ecommerce/product/_search
{
"query": {
"match_all": {}
},
"from": 0,
"size": 10
}

mget

1
2
3
4
5
6
7
POST /index/type/_mget
{
"docs":[
{"key1":"value1","key2":"value2"},
{"key3":"value3","key4":"value4"}
]
}

例如:

1
2
3
4
5
6
7
POST /ecommerce/product/_mget
{
"docs":[
{"_index":"ecommerce","_id":1},
{"_index":"ecommerce","_id":2}
]
}

搜索返回指定字段

1
2
3
4
5
6
7
GET /ecommerce/product/_search
{
"query": {
xxx
},
"_source": ["key1","key2"]
}

例如:

1
2
3
4
5
6
7
GET /ecommerce/product/_search
{
"query": {
"match_all": {}
},
"_source": ["name","price"]
}

指定字段分词搜索

1
2
3
4
5
6
7
8
GET /index/type/_search
{
"query": {
"match": {
"key1": "value1"
}
}
}

例如:

1
2
3
4
5
6
7
8
GET /ecommerce/product/_search
{
"query": {
"match": {
"name": "牙膏"
}
}
}

查询排序

1
2
3
4
5
6
7
8
9
10
11
12
13
GET /index/type/_search
{
"query": {
xxx
},
"sort": [
{
"key1": {
"order": "asc|desc"
}
}
]
}

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
GET /ecommerce/product/_search
{
"query": {
"match_all": {}
},
"sort": [
{
"price": {
"order": "desc"
}
}
]
}

查询filter

filter不涉及积分计算,因此filter的效率比普通查询的效率要高。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
GET /ecommerce/product/_search
{
"query": {
"bool": {
"must": {
"match":{
"name":"牙膏"
}
},
"filter": {
"range": {
"price": {
"gt": 10,
"lte": 30
}
}
}
}
}
}

查询phrase

跟match全文检索相反,全文检索会将搜索输入分词拆解,去倒排索引中一一匹配,只要有一个分词能在倒排索引中匹配上,就可以作为结果返回。

phrase不会将搜索输入分词,必须在指定字段值中完全包含搜索输入才算搜索匹配,作为结果返回。

例如:在match全文检索模式下,高露洁可以匹配上高露洁牙膏佳洁士牙膏;在phrase模式下,可以匹配上高露洁牙膏,但匹配不上佳洁士牙膏

1
2
3
4
5
6
7
8
GET /ecommerce/product/_search
{
"query": {
"match_phrase": {
"name": "高露洁"
}
}
}

查询高亮

1
2
3
4
5
6
7
8
9
10
11
GET /index/type/_search
{
"query": {
xxx
},
"highlight": {
"fields": {
"key1": {}
}
}
}

例如:

requset

1
2
3
4
5
6
7
8
9
10
11
12
13
GET /ecommerce/product/_search
{
"query": {
"match": {
"name": "高露洁"
}
},
"highlight": {
"fields": {
"name": {}
}
}
}

response

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
{
"took": 6,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 0.8630463,
"hits": [
{
"_index": "ecommerce",
"_type": "product",
"_id": "2",
"_score": 0.8630463,
"_source": {
"name": "高露洁牙膏",
"price": 20
},
"highlight": {
"name": [
"<em>高</em><em>露</em><em>洁</em>牙膏"
]
}
},
{
"_index": "ecommerce",
"_type": "product",
"_id": "1",
"_score": 0.2876821,
"_source": {
"name": "佳洁士牙膏",
"price": 30
},
"highlight": {
"name": [
"佳<em>洁</em>士牙膏"
]
}
}
]
}
}
>