Elasticsearch:Aggregation聚合的使用,
Elasticsearch:Aggregation聚合的使用
聚合函数(Aggregation)
Elasticsearch做查询时,有一些查询满足不了我们的查询条件,这时候就需要aggregation函数,聚合函数中有两个非常重要的语法,桶(Bucket)和指标(Metric)。Bucket可以定义文档集合,可以定义一个或多个,或者在集合中嵌套着定义集合;而Metric也称为计算度量,是以从文档中提取的值为基础进行的操作。
类比学习,es中的Bucket类似于SQL中的Group By,根据条件对元素进行分组;而Metric则和SQL中的SUM,MAX作用相似。
举一个例子,更加具象化的理解。这是一条使用了aggregations聚合的es查询语句,语句的目的是查询西京市内的各个区县的用电情况,以及每个区县里耗电最高的三个行业。
{
"size": 0,
"query": {
"bool": {
"must": [
{
"term": {
"tbCity": "西京市"
}
}
],
"must_not": {
"term": {
"isDelete": 1
}
}
}
},
"aggs": {
"CountyList": {
"terms": {
"field": "tbCounty",
"size": 2,
"order": {
"county_sum": "desc"
}
},
"aggs": {
"county_sum": {
"sum": {
"field": "lsp"
}
},
"IndustryList": {
"terms": {
"field": "industry",
"size": 3,
"order": {
"industry_sum": "desc"
}
},
"aggs": {
"industry_sum": {
"sum": {
"field": "lsp"
}
}
}
}
}
}
}
}
查询结果如下所示,只截取了aggregations聚合结果部分。
"aggregations":{
"CountyList":{
"doc_count_error_upper_bound":-1,
"sum_other_doc_count":8157,
"buckets":[
{
"key":"东港区",
"doc_count":3268,
"county_sum":{
"value":58910.11856332005
},
"IndustryList":{
"doc_count_error_upper_bound":0,
"sum_other_doc_count":906,
"buckets":[
{
"key":"钢铁",
"doc_count":177,
"industry_sum":{
"value":22498.906558190007
}
},
{
"key":"焦化",
"doc_count":11,
"industry_sum":{
"value":2145.60880998
}
},
{
"key":"水泥",
"doc_count":34,
"industry_sum":{
"value":1903.167
}
}
]
}
},
{
"key":"复兴区",
"doc_count":552,
"county_sum":{
"value":21149.51029344
},
"IndustryList":{
"doc_count_error_upper_bound":0,
"sum_other_doc_count":103,
"buckets":[
{
"key":"钢铁",
"doc_count":49,
"industry_sum":{
"value":6729.28894296
}
},
{
"key":"焦化",
"doc_count":10,
"industry_sum":{
"value":3623.8320000000003
}
},
{
"key":"冶金",
"doc_count":5,
"industry_sum":{
"value":98.039
}
}
]
}
}
]
}
}
每个buckets内的元素都会有个key和doc_count,key为聚合的聚合条件的值,doc_count为满足这个条件的文档个数,类似于SQL中的count。
本站文章为和通数据库网友分享或者投稿,欢迎任何形式的转载,但请务必注明出处.
同时文章内容如有侵犯了您的权益,请联系QQ:970679559,我们会在尽快处理。