In ElasticSearch, I have nested data structured:
{"number":1234, "predictions": [
{"variant":"blue", "startDate": "2023-02-22"},
{"variant":"red", "startDate": "2023-03-01"}
]},
...
The prediction field indicates which variants are available starting from specific dates. I want to have a query that get the product that meets the following criteria:
- check the prediction which has the start date right before the provided date.
- make sure the prediction’s variant matches the provided variant
I tried to use a nested query with range to obtain predictions from the last week (since we only get one prediction per week):
"query": { "bool": { "must": [
{"nested": {
"path":"predictions",
"query": { "bool": { "must": [
{"range": {
"predictions.startDate": {
"lte": "2023-03-02",
"gte": "2023-02-23",
} }}, {
"match": {"predictions.variant": "blue"}
} ] } } } } ] } }
But I want to modify the query to also retrieve the prediction with the most recent start date. I want to filter out products where the most recent prediction does not include the variant I specify. Expected input and result:
variant: "blue", startDate: 2023-28-02 => 1234 is in the result
variant: "blue", startDate: 2023-03-02 => 1234 is not in the result
variant: "red", startDate: 2023-04-20 => 1234 is in the result