Jordi
Jordi

Reputation: 23267

Get grouped information by week or month

We're storing our documents in a collection coll1 is storing documents like:

{
    "user" : "user1",
    "timestamp" : "2017-01-11T13:57:39.405Z",
    "matter" : "matter"
}

{
    "user" : "user1",
    "timestamp" : "2017-01-19T13:57:39.405Z",
    "matter" : "matter"
}

{
    "user" : "user1",
    "timestamp" : "2017-01-20T13:57:39.405Z",
    "matter" : "matter"
}

{
    "user" : "user2",
    "timestamp" : "2017-01-11T13:57:39.405Z",
    "matter" : "matter"
}

{
    "user" : "user2",
    "timestamp" : "2017-01-11T13:57:39.405Z",
    "matter" : "matter"
}

We need to get information like:

user - number of documents in `coll1` --> grouped by weeks or months

Desired results example:

"user1" - week 1 - 1
"user1" - week 2 - 2
"user2" - week 1 - 2

I've no idea how to get it. Any ideas?

Upvotes: 0

Views: 300

Answers (1)

Val
Val

Reputation: 217504

You can try something like this, i.e. first aggregate on the users and then for each user aggregate on the week of year. For each weekly bucket, you'll get the number of matching documents in the doc_count field.

{
  "size": 0,
  "aggs": {
    "users": {
      "terms": {
        "field": "user"
      },
      "aggs": {
        "weeks": {
          "terms": {
            "script": {
              "inline": "doc.timestamp.date.getWeekOfWeekyear()"
            }
          }
        }
      }
    }
  }
}

Note that you need to enable dynamic scripting in order for this to work.

Upvotes: 1

Related Questions