ElasticsSearch例子
查询
原始数据结构如下
这是一个银行账户的索引
1 | { |
查询所有账户,并按账户号码升序排序
1
2
3
4
5
6
7GET /bank/_search
{
"query": { "match_all": {} },
"sort": [
{ "account_number": "asc" }
]
}默认情况下,返回
10
条数据,可以通过指定size
参数来改变返回的最大数量分页查询
1
2
3
4
5
6
7
8
9GET /bank/_search
{
"query": { "match_all": {} },
"sort": [
{ "account_number": "asc" }
],
"from": 10,
"size": 10
}模糊匹配
1
2
3
4
5
6GET /bank/_search
{
"query": {
"match": { "address": "mill lane" }
}
}返回地址中包含
mill
和lane
的记录复合查询
1
2
3
4
5
6
7
8
9
10
11
12
13GET /bank/_search
{
"query": {
"bool": {
"must": [
{ "match": { "age": "40" } }
],
"must_not": [
{ "match": { "state": "ID" } }
]
}
}
}返回所有年龄在
40
岁,但是没有居住在ID
(爱荷华州)注意
must
、should
会影响评分must_not
不会影响评分范围查询
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16GET /bank/_search
{
"query": {
"bool": {
"must": { "match_all": {} },
"filter": {
"range": {
"balance": {
"gte": 20000,
"lte": 30000
}
}
}
}
}
}查询出工资在
[20000,30000]
的数据查出每个州的账户数量
1
2
3
4
5
6
7
8
9
10
11GET /bank/_search
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword"
}
}
}
}返回结果如下
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
47
48
49
50
51
52
53
54
55{
"took": 29,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped" : 0,
"failed": 0
},
"hits" : {
"total" : {
"value": 1000,
"relation": "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"group_by_state" : {
"doc_count_error_upper_bound": 20,
"sum_other_doc_count": 770,
"buckets" : [ {
"key" : "ID",
"doc_count" : 27
}, {
"key" : "TX",
"doc_count" : 27
}, {
"key" : "AL",
"doc_count" : 25
}, {
"key" : "MD",
"doc_count" : 25
}, {
"key" : "TN",
"doc_count" : 23
}, {
"key" : "MA",
"doc_count" : 21
}, {
"key" : "NC",
"doc_count" : 21
}, {
"key" : "ND",
"doc_count" : 21
}, {
"key" : "ME",
"doc_count" : 20
}, {
"key" : "MO",
"doc_count" : 20
} ]
}
}
}由于查询的时候指定
size=0
,所以hits
字段长度为0
。返回每个州的的账户数量,以及平均工资
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18GET /bank/_search
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword"
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}指定已平均工资降序排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21GET /bank/_search
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword",
"order": {
"average_balance": "desc"
}
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}
ElasticsSearch例子
You need to set
install_url
to use ShareThis. Please set it in _config.yml
.