How to get counts / stats for different periods of time?

I am trying to get the count of documents that were created for the last 10 weeks grouped by week. To get the count for the last week, I would do something like this

GET my_index/_count
{
  "query": {
    "range": {
      "document.createdOn": {
        "gte": "now-7d"
      }
    }
  }
}

But If I wanted the count for every week of the last 10 weeks, should I fire 10 queries with different gte and lte values? Or is there any way to do this in a single query?

Welcome to our community! :smiley:

Why not use an aggregation - Date range aggregation | Elasticsearch Guide [7.12] | Elastic

1 Like

Thank you:) and thanks for the suggestion. I did not know about Date Range Aggregation. I gave it a shot and this comes close to what I was looking for. Though, it returns all the documents along with the aggregations. Is there a way to make it not documents and make it return only the aggregations?

GET denormalized_spots/_search
{
  "aggs": {
    "range": {
      "date_range": {
        "field": "myObj.createdOn",
        "ranges": [
          {
            "from": "now-10d/d",
            "to": "now"
          },
          {
            "from": "now-20d/d",
            "to": "now-10d/d"
          }
        ]
      }
    }
  }
}

Edit

query parameter size=0 did the trick

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.