[Recipes] Term Level Queries - Date Ranges

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:

  1. The pipe symbol (||) seperate date from relative date math.
  2. 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:

  1. now-5M will reduce 5 months from current date. 

  2. "lt" : "2018/01/01||/y+3M" will round down to year start and add 3 months to it.

Recipe Tags: 

Learn Serverless from Serverless Programming Cookbook

Contact

Please first use the contact form or facebook page messaging to connect.

Offline Contact
We currently connect locally for discussions and sessions at Bangalore, India. Please follow us on our facebook page for details.
WhatsApp (Primary): (+91) 7411174113
Phone (Escalations): (+91) 7411174114

Business newsletter

Complete the form below, and we'll send you an e-mail every now and again with all the latest news.

About

CloudMaterials is my blog to share notes and learning materials on Cloud and Data Analytics. My current focus is on Microsoft Azure and Amazon Web Services (AWS).

I like to write and I try to document what I learn to share with others. I believe that knowledge is useless unless you share it; the more you share, the more you learn.

Recent comments

Photo Stream