# Top hit aggregation with double sorting

**URL:** <https://discuss.elastic.co/t/top-hit-aggregation-with-double-sorting/32822>\
**Category:** Elasticsearch\
**Created:** [October 23, 2015, 7:11am UTC](https://discuss.elastic.co/t/top-hit-aggregation-with-double-sorting/32822 "2015-10-23T07:11:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tom\_sharp](https://avatars.discourse-cdn.com/v4/letter/t/5daacb/32.png) [@tom\_sharp](https://discuss.elastic.co/u/tom_sharp)\
**Post date:** [October 23, 2015, 7:11am UTC](https://discuss.elastic.co/t/top-hit-aggregation-with-double-sorting/32822/1 "2015-10-23T07:11:36Z")

</div>

Hi there,

I am struggling to do a top hit aggregation that make sense on my elastic cluster.  
Here is a sample rows:

{id: 123, order: 2, bucket\_order: 2, category\_id: 0},  
{id: 456, order: 1, bucket\_order: 2, category\_id: 0},  
{id: 789, order: 3, bucket\_order: 3, category\_id: 1},  
{id: 012, order: 2, bucket\_order: 1, category\_id: 2},  
{id: 013, order: 5, bucket\_order: 1, category\_id: 2}

I would like to do a aggregation by category\_id, ordering the buckets by bucket\_order and have the order inside bucket set to the order field so that the top hit is the first one by order.

Example response (totally making this up)

{category\_id: 2, bucket\_order: 1, top\_hit : 012, all\_hits: [012,013]},  
{category\_id: 0, bucket\_order: 2, top\_hit : 456, all\_hits: [456, 123]},  
{category\_id: 1, bucket\_order: 3, top\_hit : 789, all\_hits: [789]}

Can you point me to the right direction I did a aggregation but I cannot understand how I can do the double sorting ?

---

<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:** [July 5, 2017, 11:43pm UTC](https://discuss.elastic.co/t/top-hit-aggregation-with-double-sorting/32822/2 "2017-07-05T23:43:06Z")

</div>


