# Elasticsearch Sub string on a Field

**URL:** <https://discuss.elastic.co/t/elasticsearch-sub-string-on-a-field/70217>\
**Category:** Elasticsearch\
**Created:** [December 29, 2016, 3:12pm UTC](https://discuss.elastic.co/t/elasticsearch-sub-string-on-a-field/70217 "2016-12-29T15:12:24Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jaliph](https://avatars.discourse-cdn.com/v4/letter/j/7cd45c/32.png) [@jaliph](https://discuss.elastic.co/u/jaliph)\
**Post date:** [December 29, 2016, 3:12pm UTC](https://discuss.elastic.co/t/elasticsearch-sub-string-on-a-field/70217/1 "2016-12-29T15:12:24Z")

</div>

Hi,

I have a field with MSISDNs. I need to do aggs by Substring of First 4 digits of MSISDN.

How can this be implemented in best optimised way. My Data is huge as 100GB/hr.

Can this be done by Scripted field or Inline Scripting? I'm not able to achieve this.

My Elasticsearch version is 5. We have recently moved our live instances from Elasticsearch 2.4 to 5.

Sorry if repeated.. Thanks in Advance.

---

<div class="post-metadata">

**Author:** ![spinscale](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/spinscale/32/25011_2.png) [@spinscale](https://discuss.elastic.co/u/spinscale)\
**Post date:** [December 30, 2016, 8:49am UTC](https://discuss.elastic.co/t/elasticsearch-sub-string-on-a-field/70217/2 "2016-12-30T08:49:32Z")

</div>

Hey,

even though you could do this using [a script in the terms aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/5.1/search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-script) - it would make more sense (especially when you want **fast** results, as the scripting solution it doing things at search time which should be done at index time), to index the first four digits of your field into a separate field.

There are a few different ways to do this during indexing by using different token filters. This example might not be the best, but works in this test...

```auto
PUT my_index
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_analyzer": {
          "tokenizer": "keyword",
          "filter": [
            "length_filter"
          ]
        }
      },
      "filter": {
        "length_filter": { 
          "type": "truncate",
          "length" : 4
        }
      }
    }
  }
}

POST my_index/_analyze
{
  "analyzer": "my_analyzer",
  "text": "1234567890"
}

```

--Alex

---

<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:** [January 27, 2017, 8:49am UTC](https://discuss.elastic.co/t/elasticsearch-sub-string-on-a-field/70217/3 "2017-01-27T08:49:35Z")

</div>

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