按周或按月获取分组信息

时间:2017-01-13 12:31:01

标签: elasticsearch

我们将文档存储在集合RAILS_ENV=production bundle exec rake assets:precompile中,正在存储以下文档:

coll1

我们需要获得以下信息:

{
    "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"
}

期望的结果示例:

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

我不知道怎么弄它。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情,即首先在用户上聚合,然后在一年中的每个用户聚合。对于每周一次的存储桶,您将获得doc_count字段中匹配文档的数量。

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

请注意,您需要enable dynamic scripting才能实现此目的。