# Top\_hits sort within the nested bucket

**URL:** <https://discuss.elastic.co/t/top-hits-sort-within-the-nested-bucket/353302>\
**Category:** Elasticsearch\
**Tags:** aggregations\
**Created:** [February 14, 2024, 5:16pm UTC](https://discuss.elastic.co/t/top-hits-sort-within-the-nested-bucket/353302 "2024-02-14T17:16:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mavwolverine](https://avatars.discourse-cdn.com/v4/letter/m/258eb7/32.png) [@mavwolverine](https://discuss.elastic.co/u/mavwolverine)\
**Post date:** [February 14, 2024, 5:16pm UTC](https://discuss.elastic.co/t/top-hits-sort-within-the-nested-bucket/353302/1 "2024-02-14T17:16:45Z")

</div>

document has categories array with [{"categoryId": 123, "sortOrder": 456},{"categoryId": 124, "sortOrder": 12}]

Used terms to create buckets on categoryId, now I want to sort using sortOrder inside each bucket for that specific categoryId and get top n hits.

But top\_hits seems to be using common sort order for all results.

One approache I can think of:  
write a scripted\_metric to loop through categories, match the bucket \_key and create new sortOrder field on each doc inside the bucket, then use that for top\_hits.  
question: How do I get bucket \_key?

Another approach could be:  
in the query, split all docs into separate docs per category, then apply terms and top\_hits. But I am not sure how to do that.

---

<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:** [March 13, 2024, 5:17pm UTC](https://discuss.elastic.co/t/top-hits-sort-within-the-nested-bucket/353302/2 "2024-03-13T17:17:39Z")

</div>

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