# How to access nested docs in scripted\_metric after nested aggregation

**URL:** <https://discuss.elastic.co/t/how-to-access-nested-docs-in-scripted-metric-after-nested-aggregation/254947>\
**Category:** Elasticsearch\
**Created:** [November 10, 2020, 4:19pm UTC](https://discuss.elastic.co/t/how-to-access-nested-docs-in-scripted-metric-after-nested-aggregation/254947 "2020-11-10T16:19:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![drewblin](https://avatars.discourse-cdn.com/v4/letter/d/da6949/32.png) [@drewblin](https://discuss.elastic.co/u/drewblin)\
**Post date:** [November 10, 2020, 4:19pm UTC](https://discuss.elastic.co/t/how-to-access-nested-docs-in-scripted-metric-after-nested-aggregation/254947/1 "2020-11-10T16:19:31Z")

</div>

How can i access nested docs in scripted\_metric after nested aggregation?

I make request

```auto
{
  "query": {
	"match_all": {}
  },
  "aggs": {
	"q1": {
		"nested": {
			"path": "pp"
		},
		"aggs": {
			"q2": {
				"scripted_metric": {
					"init_script": "state.transactions = []", 
					"map_script": "state.transactions.add(doc['pp.id'])",
					"combine_script": "return state.transactions",
					"reduce_script": "return states"
				}
			}
		}
	}
  }
}

```

This is just example, in more complex query i will add `filter` aggs to filter nested docs. And then i will process only matched nested docs.

I would like to process in map\_script all nested docs that current level of aggs use. But `doc['pp.id']` returns only value of one nested doc from row. And any other i try returns error - `doc['pp[0].id']` or `for (item in doc['pp'])`

---

<div class="post-metadata">

**Author:** ![drewblin](https://avatars.discourse-cdn.com/v4/letter/d/da6949/32.png) [@drewblin](https://discuss.elastic.co/u/drewblin)\
**Post date:** [November 10, 2020, 8:53pm UTC](https://discuss.elastic.co/t/how-to-access-nested-docs-in-scripted-metric-after-nested-aggregation/254947/2 "2020-11-10T20:53:55Z")

</div>

I don't know why, but `doc['pp.id']` returns some thing unpredictable (seems to be any value across all nested docs in matched outer doc).  
But `doc['pp.id'].get(0)` return exacly i expected - value of pp.id of each matched nested doc.

---

<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:** [December 8, 2020, 8:54pm UTC](https://discuss.elastic.co/t/how-to-access-nested-docs-in-scripted-metric-after-nested-aggregation/254947/3 "2020-12-08T20:54:05Z")

</div>

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