elasticsearchbuckets

Elasticsearch summing buckets


I have the following request which will return the count of all documents with a status of either "Accepted","Released" or closed.

{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "*",
            "analyze_wildcard": true
          }
        }
      ],
      "must_not": []
    }
  },
  "aggs": {
    "slices": {
      "terms": {
        "field": "status.raw",
        "include": {
          "pattern": "Accepted|Released|Closed"
        }
      }
    }
  }
}

In my case the response is:

 "buckets": [
        {
          "key": "Closed",
          "doc_count": 2216
        },
        {
          "key": "Accepted",
          "doc_count": 8
        },
        {
          "key": "Released",
          "doc_count": 6
        }
      ]

Now I'd like to add all of them up into a single field. I tried using pipeline aggregations and even tried the following sum_bucket (which apparently only works on multi-bucket):

"total":{
    "sum_bucket":{
        "buckets_path": "slices"
    }
}

Anyone able to help me out with this?


Solution

  • What I would do is to use the filters aggregation instead and define all the buckets you need, like this:

    {
      "size": 0,
      "query": {
        "bool": {
          "must": [
            {
              "query_string": {
                "query": "*",
                "analyze_wildcard": true
              }
            }
          ],
          "must_not": []
        }
      },
      "aggs": {
        "slices": {
          "filters": {
            "filters": {
              "accepted": {
                "term": {
                  "status.raw": "Accepted"
                }
              },
              "released": {
                "term": {
                  "status.raw": "Released"
                }
              },
              "closed": {
                "term": {
                  "status.raw": "Closed"
                }
              },
              "total": {
                "terms": {
                  "status.raw": [
                    "Accepted",
                    "Released",
                    "Closed"
                  ]
                }
              }
            }
          }
        }
      }
    }