Top_hits sort within the nested bucket

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.

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