{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state",
"order": {
"average_balance": "desc"
}
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}
得到的查询结果:
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 5,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"group_by_state" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [ {
"key" : "open",
"doc_count" : 2,
"average_balance" : {
"value" : 93.0
}
}, {
"key" : "close",
"doc_count" : 3,
"average_balance" : {
"value" : 88.0
}
} ]
}
}
}
本文由赛克蓝德(secisland)原创,转载请标明作者和出处。
下面这个例子比较复杂:演示了如何通过年龄组(年龄20-29岁,30-39岁,40-49),然后通过性别,最后得到是每个年龄段,每个性别的平均账户余额:
{
"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"
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}
}
}
查询出的返回结果:
{
"took" : 15,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 5,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"group_by_age" : {
"buckets" : [ {
"key" : "20.0-30.0",
"from" : 20.0,
"from_as_string" : "20.0",
"to" : 30.0,
"to_as_string" : "30.0",
"doc_count" : 1,
"group_by_gender" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [ {
"key" : "woman",
"doc_count" : 1,
"average_balance" : {
"value" : 87.0
}
} ]
}
}, {
"key" : "30.0-40.0",
"from" : 30.0,
"from_as_string" : "30.0",
"to" : 40.0,
"to_as_string" : "40.0",
"doc_count" : 3,
"group_by_gender" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [ {
"key" : "man",
"doc_count" : 2,
"average_balance" : {
"value" : 93.0
}
}, {
"key" : "woman",
"doc_count" : 1,
"average_balance" : {
"value" : 99.0
}
} ]
}
}, {
"key" : "40.0-50.0",
"from" : 40.0,
"from_as_string" : "40.0",
"to" : 50.0,
"to_as_string" : "50.0",
"doc_count" : 1,
"group_by_gender" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [ {
"key" : "woman",
"doc_count" : 1,
"average_balance" : {
"value" : 78.0
}
} ]
}
} ]
}
}
}
从上面的例子中可以看出,Elasticsearch的聚合能力是非常强大的。