# Optimisation of scripted aggregation

**URL:** <https://discuss.elastic.co/t/optimisation-of-scripted-aggregation/258324>\
**Category:** Elasticsearch\
**Created:** [December 10, 2020, 6:59pm UTC](https://discuss.elastic.co/t/optimisation-of-scripted-aggregation/258324 "2020-12-10T18:59:40Z")\
**Posts on this page:** 2\
**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:** [December 10, 2020, 6:59pm UTC](https://discuss.elastic.co/t/optimisation-of-scripted-aggregation/258324/1 "2020-12-10T18:59:40Z")

</div>

Hello!  
I have such aggregation.

```auto
	"aggs":{
		"child_id":{
			"terms":{
				"script":{
					"lang":"painless",
					"source":"params['_source']['prod_list'][params['_source']['prod_list'].indexOf(params.prod) + 1]",
					"params":{"prod":6384}
				},
				"size":1000
			}
		}
    }
EOF

```

But it is too slow. As i understand from docs - because of parsing `_source` for every matching document - it is very expensive operation.

So i need some way to optimize this aggregation.  
Idea of it - get next value from `prod_list` after matched one (`"params":{"prod":6384}`).

I tried to use `doc.prod_list` in script - but it make wrong results - items in `doc.prod_list` has different order than in `params['_source']['prod_list']`.

Does anyone have some idea?  
Thanks for everyone who can help!

---

<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:** [January 7, 2021, 6:59pm UTC](https://discuss.elastic.co/t/optimisation-of-scripted-aggregation/258324/2 "2021-01-07T18:59:43Z")

</div>

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