Search code examples
elasticsearch

ElasticSearch - filter query by length of keyword field


I want to search elasticsearch index based on length of text in one of the field. I tried various answers on SO like elasticsearch filter by length of a string field but it didn't work. Below query returns me document with longer value like %230f72e5. What is wrong with my query?

my mapping:

{
    "myindex": {
        "mappings": {
            "properties": {
                "colorcode": {
                    "type": "keyword"
                }

my query GET myindex/_search

{
    "query": {
        "bool" : {
            "must" : {
                "script" : {
                    "script" : "doc['colorcode'].size() < 5"
                }
            }
        }
    }
}

Solution

  • For calculating the length of the string you need to use the below script

    For version 7.*

    {
      "query": {
        "bool": {
          "filter": {
            "script": {
              "script": {
                "source": "doc['colorcode.keyword'].value.length() < 5",
                "lang": "painless"
              }
            }
          }
        }
      }
    }