I'm attempting to write a query that contains following logic :
if `ts` is greater than or equal to "2021-05-01T04:00:00Z" and less than "2021-10-01T04:00:00Z"
AND
the field data.data1 exists
OR
the field data.data2 exists
OR
the field data.data3 exists
OR
the field data.data4 exists
then count the number of records in the index get_test
Here is the query I'm utilizing :
GET /get_test/_count
{
"query":{
"bool": {
"must": [
{"range": {"ts": {"gte": "2021-05-01T04:00:00Z", "lt": "2021-10-01T04:00:00Z"}}},
{"exists": {"field": "data.data1"}},
{"exists": {"field": "data.data2"}},
{"exists": {"field": "data.data4"}},
{"exists": {"field": "data.data3"}}
]
}
}
}
This query executes in Elastic dev tools but 0 results are returned but records that match the above logic exist. It seems there is an implicit AND between each invocation of :
{"exists": {"field": "data.data1"}},
{"exists": {"field": "data.data2"}},
{"exists": {"field": "data.data4"}},
{"exists": {"field": "data.data3"}}
What change do I need to make to the elastic query to enable above logic ? Is there a way to define an OR
between each of the exists clauses ?
CodePudding user response:
If you have the field data
of type nested
, you must have all those criteria under a nested
query:
{
"query": {
"bool": {
"must": [
{
"range": {
"ts": {
"gte": "2021-05-01T04:00:00Z",
"lt": "2021-10-01T04:00:00Z"
}
}
},
{
"nested": {
"path": "data",
"query": {
"should": [
{
"exists": {
"field": "data.data1"
}
},
{
"exists": {
"field": "data.data2"
}
},
{
"exists": {
"field": "data.data4"
}
},
{
"exists": {
"field": "data.data3"
}
}
]
}
}
}
]
}
}
}
Note that under the nested
query, I use should
instead of must
, because you only need one of those fields to be existed (OR
)