# Sorting a terms aggregation by keys case insensitive but display the original value

**URL:** <https://discuss.elastic.co/t/sorting-a-terms-aggregation-by-keys-case-insensitive-but-display-the-original-value/270087>\
**Category:** Elastic Tips and Common Fixes\
**Created:** [April 14, 2021, 8:05am UTC](https://discuss.elastic.co/t/sorting-a-terms-aggregation-by-keys-case-insensitive-but-display-the-original-value/270087 "2021-04-14T08:05:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)\
**Post date:** [April 14, 2021, 8:05am UTC](https://discuss.elastic.co/t/sorting-a-terms-aggregation-by-keys-case-insensitive-but-display-the-original-value/270087/1 "2021-04-14T08:05:31Z")

</div>

When you normalize a `keyword` field with a `lowercase` normalizer it becomes case insensitive but what if you want to display the "original" text?

Here is a way to do that by using a `top_hits` aggregation to fetch the text from the `_source`

```auto
DELETE index
PUT index
{
  "mappings": {
    "properties": {
      "foo": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "normalizer": "lowercase"
          }
        }
      }
    }
  }
}
POST index/_bulk
{ "index" : { } }
{ "foo": "bar" }
{ "index" : { } }
{ "foo": "Bar" }
{ "index" : { } }
{ "foo": "BAZ" }
{ "index" : { } }
{ "foo": "Foo" }
{ "index" : { } }
{ "foo": "foobar" }
GET index/_search
{
  "size": 0, 
  "aggs": {
    "foo": {
      "terms": {
        "field": "foo.keyword",
        "order": { "_key": "asc" }
      },
      "aggs": {
        "hits": {
          "top_hits": {
            "size": 1,
            "_source": "foo"
          }
        }
      }
    }
  }
}

```

---

<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:** [November 4, 2022, 8:28am UTC](https://discuss.elastic.co/t/sorting-a-terms-aggregation-by-keys-case-insensitive-but-display-the-original-value/270087/2 "2022-11-04T08:28:43Z")

</div>


