# Scripting aggregation order

**URL:** <https://discuss.elastic.co/t/scripting-aggregation-order/288980>\
**Category:** Elasticsearch\
**Created:** [November 11, 2021, 10:29am UTC](https://discuss.elastic.co/t/scripting-aggregation-order/288980 "2021-11-11T10:29:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![yen\_l\_ng\_th](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/yen_l_ng_th/32/65467_2.png) [@yen\_l\_ng\_th](https://discuss.elastic.co/u/yen_l_ng_th)\
**Post date:** [November 11, 2021, 10:29am UTC](https://discuss.elastic.co/t/scripting-aggregation-order/288980/1 "2021-11-11T10:29:44Z")

</div>

Would it be possible to script the sort order of aggregations? Let me  
explain with a contrived example:

{  
"aggs": {  
"agg1": {  
"terms": {  
"field": "somefield",  
"order": {  
"avg1": "desc"  
},  
"size" : 100  
},  
"aggs": {  
"avg1": {  
"avg": {  
"field": "someotherfield"  
}  
}  
}  
}  
}

The above example will return an aggregation where the buckets are  
sorted based on the average of some other field of the bucketized  
documents. Pretty easy. What I would actually want is to do some more  
complex math such as the average of the bucketized documents times the  
number of documents in the bucket.

The metric aggregation script, as far as I can tell, does not have  
access to information of the bucket it is in.  
How to arrange something like this  
"order": {  
"\_script": {  
"script": "params.listing.indexOf((int)doc['id'].value)",  
"type": "number",  
"order": "desc",  
"params": [1,2,3]  
}  
}

---

<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 9, 2021, 10:30am UTC](https://discuss.elastic.co/t/scripting-aggregation-order/288980/2 "2021-12-09T10:30:42Z")

</div>

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