Elastic Search 聚合查询

53 阅读1分钟

在es简单查询之外,还有更高级的聚合查询,这些基本上都是会大大减少生成需求数据所需的时间。

如果说 Query 决定查哪些文档,
Aggregation 决定从这些文档里能算出什么世界。

这其中就包括:

1.value_count:统计字段非空数量

得到该索引的数量之和,一般用于列表展示

GET order_index/_search 
    { "size": 0, 
      "aggs": 
        { "order_count": 
            { "value_count": { "field": "orderId" }} 
        } 
    }

2.terms:分组聚合

等同于group by

根据所选字段,自动分组并且得出数量,一般用于列表标签展示的时候来显示各个标签有多少数据。

GET order_index/_search 
{ 
    "size": 0, 
    "aggs": 
        { "by_status": 
            { "terms": { "field": "status.keyword" }} 
        } 
 }

3.分组 + 指标聚合

根据分组的个个数据,对内求和

GET order_index/_search 
{ "size": 0, 
    "aggs": { 
    "by_status": { 
        "terms": { "field": "status.keyword" },
        "aggs": { 
            "total_amount": { "sum": { "field": "amount" } }
           } 
        }
    } 
}

4.过滤 + 聚合

通过query过滤数据,在使用agg来聚合数据。

GET order_index/_search 
{ "size": 0, 
    "query": { 
        "term": { "status.keyword": "PAID" } 
    }, 
    "aggs": { 
        "avg_amount": { "avg": { "field": "amount" } } 
    } 
}

5.date_histogram 时间聚合

根据时间格式进行聚合

GET order_index/_search 
{ "size": 0, 
    "aggs": { 
        "order_by_day": { 
            "date_histogram": { 
            "field": "createTime", "calendar_interval": "day", "format": "yyyy-MM-dd" } 
        } 
    } 
}

6.Bucket 筛选

script 进行筛选,只能在聚合之后

{"size": 0, 
    "aggs": { 
        "by_status": {
            "terms": { "field": "status.keyword" }, 
            "aggs": { 
                 "order_filter": { 
                     "bucket_selector": { 
                         "buckets_path": { "cnt": "_count" }, 
                         "script": "params.cnt >= 100"
                      }
                 }
             } 
        } 
     } 
}