How to return actual value (not lowercase) when performing search with terms aggregation? How to return actual value (not lowercase) when performing search with terms aggregation? elasticsearch elasticsearch

How to return actual value (not lowercase) when performing search with terms aggregation?


If you want to do case-insensitive search yet return exact values in your aggregations you don't need any normalizer. You can simply have a text field (which lowercases the tokens and allows case-insensitive search by default) with a keyword sub-field. You'd use the former for search and the latter for aggregations. It goes like this:

PUT index{  "mappings": {    "_doc": {      "properties": {        "foo": {          "type": "text",          "fields": {            "keyword": {              "type": "keyword"            }          }        }      }    }  }}

After indexing your two documents, your can issue a terms aggregation on foo.keyword:

GET index/_search{  "size": 2,  "aggs": {    "foo_terms": {      "terms": {        "field": "foo.keyword"      }    }  }}

And the result would look like this:

{  "took": 0,  "timed_out": false,  "_shards": {    "total": 5,    "successful": 5,    "skipped": 0,    "failed": 0  },  "hits": {    "total": 2,    "max_score": 1,    "hits": [      {        "_index": "index",        "_type": "_doc",        "_id": "2",        "_score": 1,        "_source": {          "foo": "Baz"        }      },      {        "_index": "index",        "_type": "_doc",        "_id": "1",        "_score": 1,        "_source": {          "foo": "Bar"        }      }    ]  },  "aggregations": {    "foo_terms": {      "doc_count_error_upper_bound": 0,      "sum_other_doc_count": 0,      "buckets": [        {          "key": "Bar",          "doc_count": 1        },        {          "key": "Baz",          "doc_count": 1        }      ]    }  }}