# Terms aggregation over section of a keyword

**URL:** <https://discuss.elastic.co/t/terms-aggregation-over-section-of-a-keyword/338351>\
**Category:** Elasticsearch\
**Tags:** runtime-fields\
**Created:** [July 13, 2023, 4:34pm UTC](https://discuss.elastic.co/t/terms-aggregation-over-section-of-a-keyword/338351 "2023-07-13T16:34:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![tmslara.a](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/tmslara.a/32/116339_2.png) [@tmslara.a](https://discuss.elastic.co/u/tmslara.a)\
**Post date:** [July 13, 2023, 4:34pm UTC](https://discuss.elastic.co/t/terms-aggregation-over-section-of-a-keyword/338351/1 "2023-07-13T16:34:15Z")

</div>

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,

---

<div class="post-metadata">

**Author:** ![PodarcisMuralis](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/podarcismuralis/32/122606_2.png) [@PodarcisMuralis](https://discuss.elastic.co/u/PodarcisMuralis)\
**Post date:** [July 13, 2023, 5:55pm UTC](https://discuss.elastic.co/t/terms-aggregation-over-section-of-a-keyword/338351/2 "2023-07-13T17:55:59Z")

</div>

```auto
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)"
        }
      }
    }
  }
}

```

---

<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:** [August 10, 2023, 6:52pm UTC](https://discuss.elastic.co/t/terms-aggregation-over-section-of-a-keyword/338351/4 "2023-08-10T18:52:44Z")

</div>

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