简体   繁体   English

从Java中的时间戳按月对spark数据集进行分组

[英]Group spark Dataset by month from a timestamp in java

I've loaded all rows from a table into Dataset using spark session in java. 我已使用Java中的spark会话将表中的所有行加载到数据集中。 I want to get the count of rows in each month. 我想获取每个月的行数。

I tried to create new column of month by using withColumn() so that I can later use group_by month and count(). 我试图通过使用withColumn()创建month的新列,以便以后可以使用group_by month和count()。 But I am not able to get month from timestamp. 但是我无法从时间戳中获得月份。 How can I find the count in each month from above dataset? 如何从上述数据集中找到每个月的计数?

My sample Dataset will look like this, 我的样本数据集将如下所示,

在此处输入图片说明

I believe you can use Tuple2<> type 我相信你可以使用Tuple2 <>类型

Map<Date, Integer> = myDataSetRDD.map(x -> new Tuple2<Date, Integer>(x.getDate(), 1))
            .reduceByKey((x, v) -> x + v)
            .collectAsMap();

This way you end up with a map, that has dates as keys and count of those dates as values. 这样,您最终得到一张地图,该地图将日期作为键,并将这些日期的计数作为值。 I hope that helps 希望对您有所帮助

Considering the way you have explained your problem: I tried to create new column of month by using withColumn() so that I can later use group_by month and count(). 考虑到您解释问题的方式: 我试图通过使用withColumn()创建month的新列,以便以后可以使用group_by month和count()。 But I am not able to get month from timestamp. 但是我无法从时间戳中获得月份。

You can you the static month() function provided in org.apache.spark.sql.functions package to find the month, as below: 您可以在org.apache.spark.sql.functions包中提供的static month()函数来查找月份,如下所示:

myDataset.withColumn("month", month(col("date"))).groupBy(col("month")).count().show();

where col("date") will have the timestamp (in below case : "yyyy-mm-dd HH:mm:ss" ). 其中col(“ date”)将带有时间戳(在以下情况下:“ yyyy-mm-dd HH:mm:ss”)。

Input used: 使用的输入:

1,2019-04-07 07:24:14,0,8 1,2019-04-07 07:24:14,0,8

2,2019-05-07 07:24:14,0,10 2,2019-05-07 07:24:14,0,10

5,2019-06-07 07:24:14,0,6 5,2019-06-07 07:24:14,0,6

3,2019-04-07 07:24:14,0,7 3,2019-04-07 07:24:14,0,7

This will give you an output as below: 这将为您提供如下输出:

+-----+-----+ + ----- + ----- +

|month|count| |月|计数|

+-----+-----+ + ----- + ----- +

| | 6| 6 | 1| 1 |

| | 5| 5 | 1| 1 |

| | 4| 4 | 2| 2 |

+-----+-----+ + ----- + ----- +

Hope this helps!! 希望这可以帮助!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM