# How to iterate through a nested object in a scripted metric aggregation

**URL:** https://discuss.elastic.co/t/how-to-iterate-through-a-nested-object-in-a-scripted-metric-aggregation/51397
**Category:** Elasticsearch
**Created:** [May 31, 2016, 8:23am UTC](https://discuss.elastic.co/t/how-to-iterate-through-a-nested-object-in-a-scripted-metric-aggregation/51397 "2016-05-31T08:23:25Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![agf](https://avatars.discourse-cdn.com/v4/letter/a/9fc348/32.png) [@agf](https://discuss.elastic.co/u/agf)
#### Post date: [May 31, 2016, 8:23am UTC](https://discuss.elastic.co/t/how-to-iterate-through-a-nested-object-in-a-scripted-metric-aggregation/51397/1 "2016-05-31T08:23:25Z")

</div>

```
"aggs": {
      "BV_result": {
         "scripted_metric": {
            "init_script": "_agg['BV'] = []",
            "map_script": "_agg.BV.add([_source.memSites,_source.clientId])",
            "combine_script": "result =[:]; for (element in _agg.BV) { client=element[0][0]; if(client.bankName == \"Chase (US)\"){result[element[1]]=[:]; result[element[1]]['status']=client.status;result[element[1]]['createdOn']=client.createdOn;result[element[1]]['bankName']=client.bankName;result[element[1]]['siteId']=client.siteId;result[element[1]]['isVerified']=client.isVerified;};};return result",
            "reduce_script": "output = [:]; found=0; for(value in _aggs){output+=value; found+= value.size()};return [found, output]"
         }
      }
   }

```

I'm having an issue with the above aggregation scripted\_metric query. The query works however I want to be able to iterate over a field called **\_source.memSites** which is a nested object. At the moment all it does is look at the first item of the nested object and returns the query results. What I want to do is to iterate over all the values of the nested object and extract out the relevant fields whenever **client.bankName == "Chase (US)".** Would appreciate any suggestions on how to do this.

---

<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 5, 2017, 10:47pm UTC](https://discuss.elastic.co/t/how-to-iterate-through-a-nested-object-in-a-scripted-metric-aggregation/51397/2 "2017-07-05T22:47:47Z")

</div>


