执行聚合
source:https://www.elastic.co/guide/en/elasticsearch/reference/6.4/getting-started-aggregations.html
聚合操作提供了对数据进行分组和提取统计的能力。简单的理解就是跟SQL中group by的操作一样的。
在es中,你可以在一个查询中同时进行查询命中和聚合操作返回两种结果。
这种一次简单的查询同时获取到两种结果的操作非常的强大且高效,
下面的历史是对status进行聚合,然后返回前10名聚合后的数据倒序(默认):
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword"
}
}
}
}
'
上面的操作类似于sql的:
SELECT state, COUNT(*) FROM bank GROUP BY state ORDER BY COUNT(*) DESC LIMIT 10;
返回如下:
{
"took": 29,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped" : 0,
"failed": 0
},
"hits" : {
"total" : 1000,
"max_score" : 0.0,
"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"