# Script inside an aggregation

**URL:** <https://discuss.elastic.co/t/script-inside-an-aggregation/189661>\
**Category:** Elasticsearch\
**Created:** [July 10, 2019, 6:13am UTC](https://discuss.elastic.co/t/script-inside-an-aggregation/189661 "2019-07-10T06:13:33Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pablo.e](https://avatars.discourse-cdn.com/v4/letter/p/839c29/32.png) [@pablo.e](https://discuss.elastic.co/u/pablo.e)\
**Post date:** [July 10, 2019, 6:13am UTC](https://discuss.elastic.co/t/script-inside-an-aggregation/189661/1 "2019-07-10T06:13:33Z")

</div>

Hi,

I would like to know if we can add a script inside an aggregation?  
My goal is to make a compute between fields (inside the aggregation) to get a variation.  
For example:  
...  
"aggs":{  
"group\_by\_product": {  
"terms": {  
"field": "product"  
},  
"script\_fields": {  
"test\_variation": {  
"script": {  
"lang": "painless",  
"source": "ADD A LOOP HERE FOR COMPUTATION on the field price for the same product"  
}  
}  
}  
...

And the result will be:

"aggregations" : {  
"group\_by\_product" : {  
"doc\_count\_error\_upper\_bound" : 4,  
"sum\_other\_doc\_count" : 163,  
"buckets" : [  
{  
"key" : "apple",  
**"price" : 4,**  
"doc\_count" : 29  
},  
{  
"key" : "orange",  
**"price" : 3,**  
"doc\_count" : 20

---

<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:** [August 7, 2019, 6:13am UTC](https://discuss.elastic.co/t/script-inside-an-aggregation/189661/2 "2019-08-07T06:13:40Z")

</div>

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