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"
                }
            }
        }
    }
}

2 Answers 2

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"
          }
        }
      }
    }
  }
}
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"
                }
            }
        }
    }
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.