翻译:https://www.elastic.co/guide/en/elasticsearch/reference/5.6/_executing_aggregations.html
Executing Aggregation
聚合提供了对数据进行分组和提取统计信息的能力, 考虑聚合最简单的方法是将其大致等同于SQL GROUP by和SQL聚合函数,
在Elasticsearch中,您可以执行返回结果的搜索,同时在一个响应中返回与所有结果分离的聚合结果,这是非常强大和高效的,因为您可以运行查询和多个聚合,并一次性获得两个(或两个)操作的结果,从而避免使用简洁和简化的API进行网络往返。
首先,这个示例按状态对所有帐户进行分组,然后返回按计数降序(也是默认)排序的前10个(默认)状态:
GET /bank/_search
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword"
}
}
}
}
在SQL中,上述聚合的概念类似于:
SELECT state, COUNT(*) FROM bank GROUP BY state ORDER BY COUNT(*) DESC
响应(部分显示):
{
"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" : "ME",
"doc_count" : 20
}, {
"key" : "MO",
"doc_count" : 20
} ]
}
}
}
我们可以看到ID (Idaho)有27个账户,TX (Texas)有27个账户,AL (Alabama)有25个账户,以此类推。
注意,我们将size=0设置为不显示搜索结果,因为我们只想在响应中看到聚合结果。
在前面的聚合的基础上,这个例子按状态计算平均账户余额(同样只计算按计数降序排列的前10个状态):
GET /bank/_search
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword"
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}
注意我们如何在group_by_state聚合中嵌套average_balance聚合,
这是所有聚合的常见模式。您可以在聚合中任意嵌套聚合,以从数据中提取所需的旋转摘要。
在前面的聚合的基础上,我们现在按平均余额降序排序:
GET /bank/_search
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword",
"order": {
"average_balance": "desc"
}
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}
这个例子展示了我们如何将年龄分组(20-29岁,30-39岁,40-49岁),然后按性别分组,最后得到平均账户余额,每个年龄层,每个性别:
GET /bank/_search
{
"size": 0,
"aggs": {
"group_by_age": {
"range": {
"field": "age",
"ranges": [
{
"from": 20,
"to": 30
},
{
"from": 30,
"to": 40
},
{
"from": 40,
"to": 50
}
]
},
"aggs": {
"group_by_gender": {
"terms": {
"field": "gender.keyword"
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}
}
}
还有许多其他聚合功能,我们在这里不详细介绍。如果您想进行进一步的试验,
https://www.elastic.co/guide/en/elasticsearch/reference/5.6/search-aggregations.html
聚合参考指南是一个很好的起点。