Terms aggregation over section of a keyword

Hi,

I have an index with a keyword field. The values are in the form '<code><numbers>' where I know the code is a three figures number (e.g., in '123456789' the code is 123). I want to perform an aggregation like a terms aggregation but to check the different codes contained on my index. I'm also interested on other aggregations, such as the cardinality aggregation.

Is it possible to performed the aggregation just over the code (part of the complete keyword)? I think that creating a runtime field may be useful; however I wanted to know if there's a 'native' way, maybe a way to use wildcards or something.

Many thanks in advance.
Regards,

GET your_index/_search
{
  "size": 0,
  "aggs": {
    "code_terms": {
      "terms": {
        "script": {
          "source": "doc['your_keyword_field'].value.substring(0, 3)"
        },
        "size": 10
      }
    },
    "unique_codes": {
      "cardinality": {
        "script": {
          "source": "doc['your_keyword_field'].value.substring(0, 3)"
        }
      }
    }
  }
}
1 Like

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