# What is the best way to get the average number of documents per bucket in Elasticsearch

**URL:** https://discuss.elastic.co/t/what-is-the-best-way-to-get-the-average-number-of-documents-per-bucket-in-elasticsearch/287096
**Category:** Elasticsearch
**Created:** [October 19, 2021, 1:31pm UTC](https://discuss.elastic.co/t/what-is-the-best-way-to-get-the-average-number-of-documents-per-bucket-in-elasticsearch/287096 "2021-10-19T13:31:43Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![seanletendre](https://avatars.discourse-cdn.com/v4/letter/s/dfb087/32.png) [@seanletendre](https://discuss.elastic.co/u/seanletendre)
#### Post date: [October 19, 2021, 1:31pm UTC](https://discuss.elastic.co/t/what-is-the-best-way-to-get-the-average-number-of-documents-per-bucket-in-elasticsearch/287096/1 "2021-10-19T13:31:43Z")

</div>

Suppose that we are hat maker and have an Elasticsearch index where each document corresponds to the sale of one hat. Part of the sales record is the name of the store at which the hat was  
sold. I want to find out the number of hats sold by each store, and the average number of hats sold  
over all stores. The best way I have been able to figure out is this search:

```auto
GET hat_sales/_search
{
  "size": 0,
  "query": {"match_all": {}},
  "aggs": {
    "stores": {
      "terms": {
        "field": "storename",
        "size": 65536
      },
      "aggs": {
        "sales_count": {
          "cardinality": {
            "field": "_id"
          }
        }
      }
    },
    "average_sales_count": {
      "avg_bucket": {
        "buckets_path": "stores>sales_count"
      }
    }
  }
}

```

( **Aside:** I set the size to 65536 because that is the default maximum number of buckets.)

The problem with this query is that the `sales_count` aggregation performs a redundant calculation: each `stores` bucket already has a `doc_count` property. But how can I access this `doc_count` in a buckets path?

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [November 16, 2021, 1:32pm UTC](https://discuss.elastic.co/t/what-is-the-best-way-to-get-the-average-number-of-documents-per-bucket-in-elasticsearch/287096/2 "2021-11-16T13:32:41Z")

</div>

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