0

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"
                }
            }
        }
    }
}
Kazuki
  • 1,462
  • 14
  • 34

2 Answers2

1

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"
          }
        }
      }
    }
  }
}
ESCoder
  • 15,431
  • 2
  • 19
  • 42
0

That query is wrong!
Error: A document doesn't have a value for a field! Use doc[].size()==0 to check if a document is missing a field!

The correct query is:

{
    "query": {
        "bool" : {
            "must" : {
                "script" : {
                    "script" : "doc['colorcode'].size() > 0 && doc['colorcode'].value.length() < 5"
                }
            }
        }
    }
}
Amir Bashiri
  • 129
  • 1
  • 5