# Sort over Aggregations buckets by text field over already sorted result

**URL:** https://discuss.elastic.co/t/sort-over-aggregations-buckets-by-text-field-over-already-sorted-result/366297
**Category:** Elasticsearch
**Created:** [September 10, 2024, 8:39am UTC](https://discuss.elastic.co/t/sort-over-aggregations-buckets-by-text-field-over-already-sorted-result/366297 "2024-09-10T08:39:30Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![ayanpoddar](https://avatars.discourse-cdn.com/v4/letter/a/f08c70/32.png) [@ayanpoddar](https://discuss.elastic.co/u/ayanpoddar)
#### Post date: [September 10, 2024, 8:39am UTC](https://discuss.elastic.co/t/sort-over-aggregations-buckets-by-text-field-over-already-sorted-result/366297/1 "2024-09-10T08:39:30Z")

</div>

I am currently facing an issue with sorting aggregation results on a text field in Elasticsearch. this is my query

```auto
{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "fields": [
              "username",
              "fullname"
            ],
            "query": "\"ayan\""
          }
        }
      ]
    }
  },
  "aggs": {
    "total_count": {
      "cardinality": {
        "field": "userid"
      }
    },
    "group_by_userId": {
      "terms": {
        "field": "userid",
        "size": 10,
        "include": {
          "partition": 0,
          "num_partitions": 2
        }
      },
      "aggs": {
        "latest_login": {
          "top_hits": {
            "_source": {
              "includes": [
                "username",
                "userid",
                "logintime",
              ]
            },
            "sort": [
              {
                "logintime": {
                  "order": "desc"
                }
              }
            ],
            "size": 1
          }
        }
      }
    }
  }
}

```

now i need to sort the group\_by\_userId bucket with username field or createdtimefield which depends on situation. I'm able to sort it with createdtimefield because it was a datetime field. by adding bucket\_sort with max but I could not found a way to do it with the username.
