V V
V V

Reputation: 169

Sum Bucket aggregation for the buckets with certain keys

I'm using this to aggregate my documents by type field:

       "aggs": {
        "types": {
          "terms": {
            "field": "type"
          },
          "aggs": {
            "my_sum": {
              "sum": {
                "field": "price"
              }
            }
          }
        },
        "total_sum": {
          "sum_bucket": {
            "buckets_path": "types.my_sum"
          }
        }
      }

So in each bucket there is my_sum value (the sum of all the prices of documents with the same type as that bucket key), and total_sum is the sum of all this my_sum values. What I really need is to calculate the sum of my_sum values only when the key of bucket (type) is 1 or 2. Is there any way to do this?

Thanks in advance.

Upvotes: 2

Views: 3183

Answers (1)

V V
V V

Reputation: 169

I just found out elastic search aggregation filtering values can solve my problem:

"aggs": {
    "types": {
      "terms": {
        "field": "type",
        "include": [
           1,
           2
         ]
      },
      "aggs": {
        "my_sum": {
          "sum": {
            "field": "price"
          }
        }
      }
    },
    "total_sum": {
      "sum_bucket": {
        "buckets_path": "types.my_sum"
      }
    }
  }

Upvotes: 2

Related Questions