How to use If else condition in script fields

Hi i have a query as following, i am getting the result when the "field_5" in script field have some data and when it is empty, it is not returning and is showing error.

And i want to check with if else condition in both cases(empty data case and if the filed exists data) and i need the result in both cases.

Is there anything we can do like that in Elasticsearch.

GET <index_name>/_search
{
  "_source": ["field_1","field_2","field_3","field_4","field_5"],
  "query": { 
			    "match_phrase": {
			      "<field_name>": {
        			"query": "some text to search"
      }
			    }
			    },
			  "highlight": {
			    "fields": {
			      "<field_5>": {}
			    }
			  },"script_fields": {
    "<field_5>": {
      "script": {
        "lang": "painless",
        "source": "params._source['<field_5>'].toString().length()"
      }
    }
  }
}

This works for me:

# Delete if exists
DELETE delete_if_else

# Define a simple index
PUT delete_if_else
{
  "mappings": {
    "properties": {
      "text_field": {"type": "text"},
      "keyword_field": {"type": "keyword"}
    }
  }
}

# Add some data with incomplete documents
POST delete_if_else/_bulk
{"index" : {}}
{ "text_field": "hola"}
{"index" : {}}
{"keyword_field": "mundo"}
{"index" : {}}
{ "text_field": "fo", "keyword_field": "baaaar"}

# Search and get the length if the field exits
GET delete_if_else/_search
{
  "_source": ["text_field", "keyword_field"],
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "*baaa*"
          }
        }
      ]
    }
  },
  "highlight": {
    "fields": {
      "*": {}
    }
  },
  "script_fields": {
    "scripted": {
      "script": {
        "lang": "painless",
        "source": """
if (params._source['text_field']!=null) {
  return params._source['text_field']?.toString().length();
} else {
  return 0;
}"""
      }
    }
  }
}

Some notes:

  • You don't need to put the scripted field in the _source section
  • It does not make sense to add the scripted field on the highlight section since it will return a computed value, nothing to do with the searched text
  • The if { ... } else { ...} is pretty straight forward, just check for the value to not be null and you should be good to go.
  • If you are on 8.x you may want to take a look to Runtime Fields

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