首页 > 解决方案 > How to do sum + cardinality together in aggregation in Elastic search, like sum(distinct target) with distinct( sum(amount)))

问题描述

Datatable:

target amount

10 10000

10 10000

15 12000

15 12000

Expected out put is :

target amount

1 10000

1 12000

I wanted to achieve the above result in aggregation in elastic search. Some thing like below but cardinality and sum cant be used together...

"accessorials": { "date_histogram": { "field": "invoicedt", "interval": "week", "format": "Y-MM-dd:w", "keyed": true }, "aggs": { "net_amount": { "sum": { "field": "netamt" } }, "distinct_trknumber": { "cardinality": { "field": "target" }, "sum": { "field": "amount" } }
} }

标签: elasticsearchelasticsearch-5

解决方案


术语聚合可用于获得不同的目标和数量

询问:

{
  "size": 0, 
  "aggs": {
    "targets": {
      "terms": {
        "field": "target",
        "size": 10
      },
      "aggs": {
        "amount": {
          "terms": {
            "field": "amount",
            "size": 10
          },
          "aggs": {
            "count": {
              "cardinality": {
                "field": "amount"
              }
            }
          }
        }
      }
    }
  }
}

结果:

"aggregations" : {
    "targets" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 10,
          "doc_count" : 2,
          "amount" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : 10000,
                "doc_count" : 2,
                "count" : {
                  "value" : 1
                }
              }
            ]
          }
        },
        {
          "key" : 15,
          "doc_count" : 2,
          "amount" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : 12000,
                "doc_count" : 2,
                "count" : {
                  "value" : 1
                }
              }
            ]
          }
        }
      ]
    }
  }

推荐阅读