Once we've ruled out doc upserts/updates there are essentially 2 approaches to this: script_fields
or filter aggregations
.
Let's first assume your mapping looks similar to:
{
"mappings": {
"properties": {
"delivery_datetime": {
"type": "object",
"properties": {
"dateOnly": {
"type": "date",
"format": "dd.MM.yyyy"
}
}
}
}
}
}
Now, if we filter all our packages by, say, its ID and want to know in which due-state it is, we can create 3 script fields like so:
GET parcels/_search
{
"_source": "timeframe_*",
"script_fields": {
"timeframe_due": {
"script": {
"source": "doc['delivery_datetime.dateOnly'].value.dayOfMonth == params.nowDayOfMonth",
"params": {
"nowDayOfMonth": 8
}
}
},
"timeframe_overdue": {
"script": {
"source": "doc['delivery_datetime.dateOnly'].value.dayOfMonth < params.nowDayOfMonth",
"params": {
"nowDayOfMonth": 8
}
}
},
"timeframe_not_due": {
"script": {
"source": "doc['delivery_datetime.dateOnly'].value.dayOfMonth > params.nowDayOfMonth",
"params": {
"nowDayOfMonth": 8
}
}
}
}
}
which'll return something along the lines of:
...
"fields" : {
"timeframe_due" : [
true
],
"timeframe_not_due" : [
false
],
"timeframe_overdue" : [
false
]
}
It's trivial and the date math has a significant weak point that'll be addressed below.
Alternatively, we can use 3 filter aggregations and similarly filter only 1 document in question out like so:
GET parcels/_search
{
"size": 0,
"query": {
"ids": {
"values": [
"my_id_thats_due_today"
]
}
},
"aggs": {
"due": {
"filter": {
"range": {
"delivery_datetime.dateOnly": {
"gte": "now/d",
"lte": "now/d"
}
}
}
},
"overdue": {
"filter": {
"range": {
"delivery_datetime.dateOnly": {
"lt": "now/d"
}
}
}
},
"not_due": {
"filter": {
"range": {
"delivery_datetime.dateOnly": {
"gt": "now/d"
}
}
}
}
}
}
yielding
...
"aggregations" : {
"overdue" : {
"doc_count" : 0
},
"due" : {
"doc_count" : 1
},
"not_due" : {
"doc_count" : 0
}
}
Now the advantages of the 2nd approach are as follows:
There are no scripts involved -> faster execution.
More importantly, you don't have to worry about day-of-month math like Dec 15th being later than Nov 20th but the trivial day-of-month comparison would yield otherwise. You can implement something similar in your scripts but more complexity equals worse execution speed.
You can ditch the ID filtering and use those aggregated counts in an internal dashboard. Possibly even a customer dashboard but regular customers rarely have lots of parcels which would be reasonable to aggregate.