FlyingBurger
FlyingBurger

Reputation: 1372

how can I query last month data in elasticsearch

I want to get last month data from elasticsearch.

For example, today is 09/08/2019, so the last month data should be from 01/07/2019 - 31/07/2019.

I try to set the time range "gte": "now+1m-1M/M", "gte" is greater than or equal to, it will return the data from 01/07/2019 (the first day of last month) to 09/08/2019 (today).

I think to make it query with the correct date range, I need to specify the upper bound using "lte" - less than or queal to. How can I define the last day of the month?

{
  "size": 0,
  "query": {
    "range": {
      "date": {
        "gte": "now+1m-1M/M",
        "time_zone": "+00:00"
      }
    }
  }
}

Upvotes: 7

Views: 7900

Answers (1)

Val
Val

Reputation: 217504

What I would do is to add an lt constraint on the beginning of the current month, like this:

{
  "size": 0,
  "query": {
    "range": {
      "date": {
        "gte": "now+1m-1M/M",
        "lt": "now/M",
        "time_zone": "+00:00"
      }
    }
  }
}

Upvotes: 15

Related Questions