Elasticsearch aggregations API

聚合能力

  • Aggregation API 类似 SQL 中的 GROUP BY 语句,可以以某个字段来进行分组。
  • Aggregation API 支持分级分组,多级的分组过程是由外到里的。
  • Aggregation API 除了分组功能,依据 API 的不同也能对每一组数据进行不同的分析(比如计数/求和等)。

搜索示例

搜索语句

{
    "aggs": {
        "1111111": {
            "filter": {},
            "aggs": {
                "2222222": {
                    "date_histogram": {
                        "field": "基本.上报时间",
                        "interval": "1M"
                    },
                    "aggs": {
                        "333333": {
                            "cardinality": {
                                "field": "基本.网关"
                            }
                        }
                    }
                }
            }
        }
    }
}

搜索结果

解释:

  1. 由于 11111 并没有执行实际的搜索(包含了一个空的 filter 和 aggs 2222),所以 1111 并没有对原始数据进行任何处理,而是直接进入第二个 aggs 【最外层聚合】
  2. 由于 22222 使用了 date_histogram 聚合语句,所以把数据按月聚集在一起,每一个子对象中还做了个数量统计: "doc_count": 3 【中间层聚合】
  3. 由于 33333 使用了 cardinality 聚合语句,所以把由 22222 输出的 buckets 中的每个子对象,再执行 uniq 操作,并得出去重后的数量: "value": 1 【最里层聚合】
{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "failed": 0
  },
  "hits": {
    "total": 26,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "1111111": {
      "2222222": {
        "buckets": [
          {
            "333333": {
              "value": 1
            },
            "key_as_string": "2016/03/01 00:00:00",
            "key": 1456790400000,
            "doc_count": 3
          },
......
{ "333333": { "value": 1 }, "key_as_string": "2016/12/01 00:00:00", "key": 1480550400000, "doc_count": 3 } ] }, "doc_count": 26 } } }

 

原文地址:https://www.cnblogs.com/licongyu/p/5312020.html