Problem:
Demo range with dates. Show how we can add or substract dates. Show how we can round off date.
Solution Summary:
We can use range query with date math.
Prerequisites:
Set up accounts index from accounts.json as explained in the link. Make sure you add opening_date field as given in the link.
Solution Steps:
Case 1 - Simple Date Range
GET /accounts/_search
{
"query": {
"range" : {
"opening_date" : {
"gte" : "2018/01/01",
"lte" : "2018/03/31"
}
}
}
}
Note: "gte" is greater than or equal to, "gt" is greater than, "lte" is "less than or equal to", "lt" is less than.
Case 2 - Range With Relative Date (Date Math)
GET /accounts/_search
{
"query": {
"range" : {
"opening_date" : {
"gte" : "2018/01/01",
"lte" : "2018/01/01||+2M"
}
}
}
}
Note:
- The pipe symbol (||) seperate date from relative date math.
- y = year, M = month, m = minute, d = day.
Case 3 - Rounding off date
GET /accounts/_search
{
"query": {
"range" : {
"opening_date" : {
"gte" : "2018/01/01",
"lte" : "2018/01/01||/y"
}
}
}
}
Note: This will print all records as /y rounds up to next year with lte. Change "lte" to "lt" and you will see no records as "lt" rounds down.
Note: "gt" round up, "gte" round down, "lt" round down, "lte" round up.
Case 4 - Relative Date with Rounding off
GET /accounts/_search
{
"query": {
"range" : {
"opening_date" : {
"gte" : "now-5M",
"lt" : "2018/01/01||/y+3M"
}
}
}
}
Note:
-
now-5M will reduce 5 months from current date.
-
"lt" : "2018/01/01||/y+3M" will round down to year start and add 3 months to it.
Recent comments