# Nested Aggregation in a Transforms Script and collect value

**URL:** <https://discuss.elastic.co/t/nested-aggregation-in-a-transforms-script-and-collect-value/229888>\
**Category:** Elasticsearch\
**Created:** [April 27, 2020, 3:37am UTC](https://discuss.elastic.co/t/nested-aggregation-in-a-transforms-script-and-collect-value/229888 "2020-04-27T03:37:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![aviman](https://avatars.discourse-cdn.com/v4/letter/a/eada6e/32.png) [@aviman](https://discuss.elastic.co/u/aviman)\
**Post date:** [April 27, 2020, 3:37am UTC](https://discuss.elastic.co/t/nested-aggregation-in-a-transforms-script-and-collect-value/229888/1 "2020-04-27T03:37:58Z")

</div>

What is the syntax for loop through all the buckets inside the map statement

Below is my aggregation code:

```auto
    "aggs": {  
 "account_agg" : { 
    "terms": { 
                "field": "client"},
                "aggs" : {
                "account_month" : {
                     "terms" : {
                         "field" : "month",
                         "size" : 7
                    } ,
                       "aggs":{
                         "min_txncount":{
              "min":{
                "field":"txn_count"
              }
            },
            "max_txncount":{
              "max":{
                "field":"txn_count"
              } } } } }
                     
                 }
     
   }

```

Below is my transform script:

```auto
 "transform" : {
      "script":
      """
        return ['txn_diff': ctx.payload.aggregations.account_agg.buckets.stream().map( t -> {                                                   
                return ['account': t.key]}).collect(Collectors.toList())]
      """
    }

```

But, I want to collect the key and min\_txncount & max\_txncount from account\_month buckets.

How to place the for loop:

My for loop construct:

```auto
for (int i = 0; i < ctx.payload.aggregations.account_agg.buckets.size(); i++)
	{for (int j = 0; j < ctx.payload.aggregations.account_agg.buckets[i].account_agg.buckets.size(); j++){ if ( ctx.payload.aggregations.account_agg.buckets[i].account_agg.buckets[j].min_txncount.value != ctx.payload.aggregations.account_agg.buckets[i].account_agg.buckets[j].max_txncount.value)

```

Thanks & Regards

---

<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:** [May 25, 2020, 3:38am UTC](https://discuss.elastic.co/t/nested-aggregation-in-a-transforms-script-and-collect-value/229888/2 "2020-05-25T03:38:07Z")

</div>

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