# Aggregate over bucket result

**URL:** <https://discuss.elastic.co/t/aggregate-over-bucket-result/236201>\
**Category:** Elasticsearch\
**Created:** [June 8, 2020, 3:35pm UTC](https://discuss.elastic.co/t/aggregate-over-bucket-result/236201 "2020-06-08T15:35:26Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Johnny2Chen](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/johnny2chen/32/69935_2.png) [@Johnny2Chen](https://discuss.elastic.co/u/Johnny2Chen)\
**Post date:** [June 8, 2020, 3:35pm UTC](https://discuss.elastic.co/t/aggregate-over-bucket-result/236201/1 "2020-06-08T15:35:26Z")

</div>

I want to aggregate or count the result in the bucket. for example:

```auto
    {
     ID: 1,
     customer_name: a,
     age: 21,
     other_field: x
    },
    {
     ID: 2,
     customer_name: a,
     age: 25,
     other_field: x
    }
    {
     ID: 3,
     customer_name: a,
     age: 32,
     other_field: x
    }
    {
     ID: 4,
     customer_name: b,
     age: 24,
     other_field: x
    }
    {
     ID: 5,
     customer_name: b,
     age: 33,
     other_field: x
    }
    {
     ID: 6,
     customer_name: b,
     age: 17,
     other_field: y
    },
    {
     ID: 7,
     customer_name: c,
     age: 34,
     other_field: x
    },
    {
     ID: 8,
     customer_name: c,
     age: 26,
     other_field: y
    }

```

my query is:

```auto
"query": {
  "bool": {
    "must": { "match": { "other_field": "x" }},
    }
  }

```

hit doc's ID are [1,2,3,4,5,7]

What I want to do is find out every customer's youngest hit docs

my aggregate query is

```auto
    "aggs": {
        "distinct_user": {
            "terms": {
                "field": "customer_name",
                "size": 100
            },
            "aggs": {
                "youngest": {
                    "min": {
                        "field": "AGE"
                    }
                }
            }
        }
    }

```

result:

```auto
bucket: [
 {
  "key": "a",
  "doc_count": 3,
  "youngest": {
  "value": 21
   }
 },
 {
  "key": "b",
  "doc_count": 2,
  "youngest": {
  "value": 24
   }
 },
 {
  "key": "c",
  "doc_count": 1,
  "youngest": {
  "value": 34
   }
 }
]

```

than using range aggregate to calculate age distribution

21~30: 2 31~40: 1

Is there any way to aggregate over bucket result? Or something work around?

---

<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:** [July 6, 2020, 3:35pm UTC](https://discuss.elastic.co/t/aggregate-over-bucket-result/236201/2 "2020-07-06T15:35:30Z")

</div>

Closed on July 6, 2020, 3:35pm UTC

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