按星期几和小时数的Elasticsearch聚合 [英] Elasticsearch Aggregation by Day of Week and Hour of Day

查看:232
本文介绍了按星期几和小时数的Elasticsearch聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类型的文档:

[{"msg":"hello", date: "some-date"},{"msg":"hi!", date: "some-date"}, ...

我想按星期几获取文件数。例如,x消息是在星期一发送的,y消息是在星期二发送的,依此类推。

I want to have the count of documents by day of week. For example x messages were sent on Monday and y were sent on Tuesday and so on.

我使用date_histogram进行汇总,但它按日返回文档。它确实返回了当天,但是说 22周三和 29周三作为单独的汇总文档返回。

I have used date_histogram with aggregation but it returns me the documents day wise. It does return me the day, but say "Wed, 22" and "Wed, 29" are returned as separate aggregation documents.

这与> Elasticsearch-按周和小时的天分组,但没有答案这个问题,所以我重新发布。
根据那里的建议,它要求我对key_as_string进行术语聚合,但是我需要为每个对象添加doc_count而不是仅仅计算术语。我也不知道如何在嵌套聚合中使用key_as_string。

This is somewhat related to Elasticsearch - group by day of week and hour but there is no answer to that question so I am reposting it. According to the suggestion there it asks me to do term aggregation on key_as_string, but I need to add doc_count for every object instead of just count the terms. I also don't know how to use key_as_string in the nested aggregation.

这是我尝试过的方法:

"aggs" : {
                "posts_over_days" : {
                    "date_histogram" : { 
                        "field" : "created_time", 
                        "interval": "day",
                        "format": "E" 
                    }
                }


推荐答案

此线程

为了适应您的问题,我们需要一个将日期转换成一天中的小时和星期几的脚本:

Adapting the solution to your problem, we need to make a script to convert the date into the hour of day and day of week:

Date date = new Date(doc['created_time'].value) ; 
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat('EEE, HH');
format.format(date)

并在查询中使用它:

{
    "aggs": {
        "perWeekDay": {
            "terms": {
                "script": "Date date = new Date(doc['created_time'].value) ;java.text.SimpleDateFormat format = new java.text.SimpleDateFormat('EEE, HH');format.format(date)"
            }
        }
    }
}

这篇关于按星期几和小时数的Elasticsearch聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆