# Specify bucket-wise sort order

**URL:** <https://discuss.elastic.co/t/specify-bucket-wise-sort-order/366932>\
**Category:** Elastic Search\
**Created:** [September 23, 2024, 5:55am UTC](https://discuss.elastic.co/t/specify-bucket-wise-sort-order/366932 "2024-09-23T05:55:02Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![anant\_saxena](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/anant_saxena/32/137789_2.png) [@anant\_saxena](https://discuss.elastic.co/u/anant_saxena)\
**Post date:** [September 23, 2024, 5:55am UTC](https://discuss.elastic.co/t/specify-bucket-wise-sort-order/366932/1 "2024-09-23T05:55:02Z")

</div>

I have a use case where I need to get buckets (with documents) and depending on the bucket, specify different field to sort by.  
All documents have the field, say, "type", which I will aggregate by. And for just 1 type I want the documents returned to be sorted by createdTime. Rest all documents should be sorted by modifiedTime. Can I achieve this within a single aggregation?

I know I can achieve my goal with 2 parallel partial aggregations (separate the one type from the rest).

> **[Bucket sort aggregation | Elasticsearch Guide \[8.15\] | Elastic](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-sort-aggregation.html)**

I assume this could have been not added because this is a rarer case where the querier knows the key of the buckets that are going to be returned. Let me know if this can be done in a single aggregation?

Thanks for the help!

---

<div class="post-metadata">

**Author:** ![Kathleen\_DeRusso](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/kathleen_derusso/32/132039_2.png) [@Kathleen\_DeRusso](https://discuss.elastic.co/u/Kathleen_DeRusso)\
**Post date:** [September 23, 2024, 3:17pm UTC](https://discuss.elastic.co/t/specify-bucket-wise-sort-order/366932/2 "2024-09-23T15:17:34Z")

</div>

I believe the only way you could do this with a single aggregation, is if you created a third field (let's say for sake of conversation `sortTime`) and populated it with the correct data based on type. I haven't played with it, but you might be able to use [runtime fields](https://www.elastic.co/guide/en/elasticsearch/reference/current/runtime.html) to do what you want.

---

<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:** [October 21, 2024, 3:18pm UTC](https://discuss.elastic.co/t/specify-bucket-wise-sort-order/366932/3 "2024-10-21T15:18:08Z")

</div>

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