Trying to build a query for documents like:
{
"name" : "Bob",
"grades" : [
{
"year" : 2010,
"grade": 8,
},
{
"year" : 2018,
"grade": 7,
},
{
"year" : 2019,
"grade": 4,
}
]
},
{
"name" : "Alice",
"grades" : [
{
"year" : 2005,
"grade": 3,
},
{
"year" : 2016,
"grade": 8,
},
{
"year" : 2018,
"grade": 7,
},
{
"year" : 2019,
"grade": 6,
}
]
}
I have a range of years e.g. from 2010 till 2020. Query should return a document if for all available years (in document) in range (from 2010 till 2020) grades are > 5. If there are grades <= 5 outside the interested range of years, we do not care and those should not affect the final result in any way. So basically only document with Alice should be returned. After looking into the Elasticsearch documentation, can't find the solution (most likely I just miss something). I'm able to construct a query if there are no gaps in years, but in my case there are gaps. So my query just drops such documents. Current query:
{
"query": {
"bool": {
"must": [
{
"nested": {
"query": {
"bool": {
"must": [
{
"term": {
"grades.year": {"value": 2010}
}
},
{
"range": {
"grades.grade": {"from": 5}
}
}
]
}
},
"path": "grades"
}
},
{
"nested": {
"query": {
"bool": {
"must": [
{
"term": {
"grades.year": {"value": 2011}
}
},
{
"range": {
"grades.grade": {"from": 5}
}
}
]
}
},
"path": "grades"
}
},
....
]
}
}
}
Probably I definitely miss something. Is it possible?
UPDATE
I've added year 2005 with grade 3 to Alice` grades. So now Alice still should be matched as year 2005 is outside the interested range.
Thanks!
Looks like I've found the solution! Thanks to @Bhavya for directing me. Basically some additional boolean logic in place. I've end up with the following query:
{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "grades",
"query": {
"bool": {
"must": [
{
"range": {
"grades.year": {
"gte": 2010,
"lte": 2020
}
}
}
]
}
}
}
}
],
"must_not": {
"nested": {
"path": "grades",
"query": {
"bool": {
"should": [
{
"bool": {
"must": [
{
"term": {
"grades.year": {
"value": 2010
}
}
},
{
"range": {
"grades.grade": {
"lte": 5
}
}
}
]
}
},
...
...
...
...
...
]
}
}
}
}
}
}
}