Filtering the response into the "Avg Bucket Aggregation"

Hi all.

I'm trying to use "Avg Bucket Aggregation".
This is the example given in the help page of Elasticsearch site.

    POST /_search
    {
      "size": 0,
      "aggs": {
        "sales_per_month": {
          "date_histogram": {
            "field": "date",
            "calendar_interval": "month"
          },
          "aggs": {
            "sales": {
              "sum": {
                "field": "price"
              }
            }
          }
        },
        "avg_monthly_sales": {
          "avg_bucket": {
            "buckets_path": "sales_per_month>sales" 
          }
        }
      }
    }

Referring to your example, the aggregation returns a result formatted like this

  {
      "took": 11,
      "timed_out": false,
      "_shards": ...,
      "hits": ...,
      "aggregations": {
         "sales_per_month": {
            "buckets": [
               {
                  "key_as_string": "2015/01/01 00:00:00",
                  "key": 1420070400000,
                  "doc_count": 3,
                  "sales": {
                     "value": 550.0
                  }
               },
               {
                  "key_as_string": "2015/02/01 00:00:00",
                  "key": 1422748800000,
                  "doc_count": 2,
                  "sales": {
                     "value": 60.0
                  }
               },
               {
                  "key_as_string": "2015/03/01 00:00:00",
                  "key": 1425168000000,
                  "doc_count": 2,
                  "sales": {
                     "value": 375.0
                  }
               }
            ]
         },
         "avg_monthly_sales": {
             "value": 328.33333333333333
         }
      }
   }

I would only be interested in the part of the answer that contains the value "avg_monthly_sales" and not the buckets of the date histogram, i.e something like this:

    {
       "took": 11,
       "timed_out": false,
       "_shards": ...,
       "hits": ...,
       "aggregations": {
    "avg_monthly_sales": {
              "value": 328.33333333333333
          }
       }
    }

Is there any way to achieve this behavior?

Thanks for your help,
Famas

Not sure I got the question right, but wouldn't that mean in your case that you are just interested in the avg of the price field for a certain time range - which would be a range query with the correct start & end date?

Hi Alexander.
Thank you for your answer!

The query actually calculates the average of the total monthly sales
ElasticSearch Reference

It works very well, but when the buckets to be transferred are many, it would be better, for efficiency questions, to be able to transfer only the average data and not all the buckets that were used to calculate this average.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.