# Sort terms aggregation hits by topHits first hit

**URL:** <https://discuss.elastic.co/t/sort-terms-aggregation-hits-by-tophits-first-hit/202952>\
**Category:** Elasticsearch\
**Created:** [October 10, 2019, 6:23am UTC](https://discuss.elastic.co/t/sort-terms-aggregation-hits-by-tophits-first-hit/202952 "2019-10-10T06:23:52Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Hanan\_Aharonof](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/hanan_aharonof/32/55668_2.png) [@Hanan\_Aharonof](https://discuss.elastic.co/u/Hanan_Aharonof)\
**Post date:** [October 10, 2019, 6:23am UTC](https://discuss.elastic.co/t/sort-terms-aggregation-hits-by-tophits-first-hit/202952/1 "2019-10-10T06:23:52Z")

</div>

Hi,

I'm running the following query:

GET security/\_search  
{  
"size": 0,  
"query": {  
"match\_all": {}  
},  
"aggs": {  
"aggBy": {  
"terms": {  
"field": "assetType",  
"size": 250,  
"order": {  
"\_count": "asc"  
}  
},  
"aggs": {  
"topHits": {  
"top\_hits": {  
"size": 1,  
"sort": [{  
"createdAt": {  
"order": "desc"  
}  
}]  
}  
}  
}  
}  
}  
}

This groups all documents by their 'assetType' value, and the topHits picks for each group the document with the most recent 'createdAt' timestamp.  
My question is, after these results are obtained, is there a way to sort them by a third field. i.e. sort the terms aggregation result by field of the first result of the inner topHits aggregation

Thanks!

---

<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:** [November 7, 2019, 6:23am UTC](https://discuss.elastic.co/t/sort-terms-aggregation-hits-by-tophits-first-hit/202952/2 "2019-11-07T06:23:54Z")

</div>

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