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
_sourcesection - It does not make sense to add the scripted field on the
highlightsection 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 benulland you should be good to go. - If you are on 8.x you may want to take a look to Runtime Fields