【问题标题】:How to calculate the number of empty bucket when aggregating by days?按天聚合时如何计算空桶数?
【发布时间】:2017-10-23 21:12:45
【问题描述】:

我想获取一个人在 5 月份在一个城镇停留的天数(Month 等于 5)。

这是我的查询,但它给出了 myindexPersonID 等于 111Month 等于 5 的条目数。例如,这个查询可能给我一个类似 90 的输出,但每月最多有 31 天。

GET myindex/_search?
{
 "size":0,
 "query": {
    "bool": {
      "must": [
        { "match": {
          "PersonID": "111"
        }},
        { "match": {
          "Month": "5"
        }}
      ]
    } },
   "aggs": {
    "stay_days": {
     "terms" : {
      "field": "Month"
     }
    }
   }
}

myindex 我有像DateTime 这样的字段,其中包含一个人被相机注册的日期和时间,例如2017-05-01T00:30:08"。因此,同一个人在一天内可能会多次经过相机,但应计为 1。

如何更新我的查询以计算每月的天数而不是相机的拍摄次数?

【问题讨论】:

  • 你能提供你的映射吗?

标签: elasticsearch elasticsearch-plugin


【解决方案1】:

假设您的 DateTime 字段名为 datetime,一种考虑方法是 DateHistogram 聚合:

{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "PersonID": "111"
          }
        },
        {
          "range": {
            "datetime": {
              "gte": "2017-05-01",
              "lt": "2017-06-01"
            }
          }
        }
      ]
    }
  },
  "aggregations": {
    "my_day_histogram": {
      "date_histogram": {
        "field": "datetime",
        "interval": "1d",
        "min_doc_count": 1
      }
    }
  }
}
  • 注意,在must 子句中,我使用了range 术语和datetime 字段(不是必需的,但您可能认为Month 字段是多余的)。此外,您可能需要将范围术语中的日期格式编辑到映射中
  • my_day_histogram:通过设置 "interval": "1d" 将数据划分为不同日期的桶。
  • "min_doc_count": 1 删除包含零个文档的存储桶。

其他方法,删除第 5 个月的范围/匹配并扩展一年中每一天的直方图。 这也可以与月份直方图聚合,如下所示:

  "aggregations": {
    "my_month_histogram": {
      "date_histogram": {
        "field": "first_timestamp",
        "interval": "1M",
        "min_doc_count": 1
      },
      "aggregations": {
        "my_day_histogram": {
          "date_histogram": {
            "field": "first_timestamp",
            "interval": "1d"
          }
        }
      }
    }
  }

我很清楚,在这两种方式中,您都需要计算表示天数的桶数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2014-08-10
    • 1970-01-01
    • 2015-01-08
    相关资源
    最近更新 更多