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

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

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"
          }
        }
      }
    }
  }
}
3 Likes