What I want to achieve is that:
- When a field doesn't exist, this document should be returned.
- When a field exists but its value is an empty array, this document should NOT be returned.
It seems that I cannot use exists query because it doesn't differentiate the two cases.
Should I use something like below?
GET /_search
{
"query": {
"bool": {
"must_not": {
"exists": {
"field": "weekly_hours.monday_hours"
}
},
"filter": {
"script": {
"script": {
"source": "doc['weekly_hours.monday_hours'].size != 0",
"lang": "painless"
}
}
}
}
}
}
This way, both the situations mentioned above will return true
in the must_not
section, then in the filter
the 2nd situation will be filtered out as its size is 0.
Is that correct?
Is there any simpler way to do it?
Thanks in advance!
Update:
I tried the script mentioned above. I guess the idea works but an exception Fielddata is not supported on field [weekly_hours.monday_hours] of type [date_range]
occurred, as shown below.
{
"took": 12,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 4,
"failed": 1,
"failures": [
{
"shard": 3,
"index": "items",
"node": "jRtjvF1mTzG_jPTqkDo2uA",
"reason": {
"type": "script_exception",
"reason": "runtime error",
"script_stack": [
"org.elasticsearch.index.mapper.MappedFieldType.fielddataBuilder(MappedFieldType.java:103)",
"org.elasticsearch.index.fielddata.IndexFieldDataService.getForField(IndexFieldDataService.java:111)",
"org.elasticsearch.search.lookup.LeafDocLookup$1.run(LeafDocLookup.java:87)",
"org.elasticsearch.search.lookup.LeafDocLookup$1.run(LeafDocLookup.java:84)",
"java.security.AccessController.doPrivileged(Native Method)",
"org.elasticsearch.search.lookup.LeafDocLookup.get(LeafDocLookup.java:84)",
"doc['weekly_hours.monday_hours'].size() != 0",
" ^---- HERE"
],
"script": "doc['weekly_hours.monday_hours'].size() != 0",
"lang": "painless",
"caused_by": {
"type": "illegal_argument_exception",
"reason": "Fielddata is not supported on field [weekly_hours.monday_hours] of type [date_range]"
}
}
}
]
},
"hits": {
"total": 0,
"max_score": null,
"hits": []
}
}
The monday_hours
field is of type date_range
.
Does that mean I cannot use script on this field at all?
If so, how to achieve the effect I described at the beginning of the question?
Really need help here...