Ron Ziroby Romero
Ron Ziroby Romero

Reputation: 9459

Return a single aggregate value from Elasticsearch

I'm working on Elasticsearch aggregations, and I would like to get a single value that aggregates the values for all records. I can cheat with a "Range >= 0" aggregation, but is there a more idiomatic way?

My kludgy query is:

{
  "size": 0,
  "aggs": { 
    "all": { 
      "range": {
        "field": "price", 
        "ranges": [{"from": 0}] }
       }
    },
    "aggs": {
      "total price": {
         "avg": {"field": "price"}}
       }
    }
}

Upvotes: 0

Views: 165

Answers (1)

jhilden
jhilden

Reputation: 12439

ES has built this into the "stats" aggregation for you, use the "sum" result.

GET devdev/alert/_search
{
  "size": 0, 
 "aggs": {
   "ag1": {
     "stats": {
       "field": "price"
     }
   }
 }
}

Result:

{
   "took": 483,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 4129196,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "ag1": {
         "count": 4119334,
         "min": -1,
         "max": 7004,
         "avg": 5.29581966405249,
         "sum": 21815250
      }
   }
}

Upvotes: 1

Related Questions