从 java 中的时间戳按月对 spark 数据集进行分组
Group spark Dataset by month from a timestamp in java
我已使用 java 中的 spark 会话将 table 中的所有行加载到数据集中。我想获取每个月的行数。
我尝试使用 withColumn() 创建新的月份列,以便以后可以使用 group_by 月份和 count()。但我无法从时间戳中获取月份。如何从上面的数据集中找到每个月的计数?
我的示例数据集将如下所示,
我相信你可以使用 Tuple2<> 类型
Map<Date, Integer> = myDataSetRDD.map(x -> new Tuple2<Date, Integer>(x.getDate(), 1))
.reduceByKey((x, v) -> x + v)
.collectAsMap();
这样您就可以得到一张地图,其中日期作为键,这些日期的计数作为值。
希望对您有所帮助
考虑到您解释问题的方式:
我尝试使用 withColumn()
创建新的月份列,以便以后可以使用 groupBy()
月份和 count()
。但是我无法从时间戳中获取月份。
您可以使用org.apache.spark.sql.functions
包中提供的静态month()
函数来查找月份,如下所示:
myDataset.withColumn("month", month(col("date"))).groupBy(col("month")).count().show()
其中 col("date")
将具有时间戳(在下面的情况下:"yyyy-mm-dd HH:mm:ss"
)。
使用的输入:
1,2019-04-07 07:24:14,0,8
2,2019-05-07 07:24:14,0,10
5,2019-06-07 07:24:14,0,6
3,2019-04-07 07:24:14,0,7
这将为您提供如下输出:
+-----+-----+
|month|count|
+-----+-----+
| 6| 1|
| 5| 1|
| 4| 2|
+-----+-----+
希望对您有所帮助!!
我已使用 java 中的 spark 会话将 table 中的所有行加载到数据集中。我想获取每个月的行数。
我尝试使用 withColumn() 创建新的月份列,以便以后可以使用 group_by 月份和 count()。但我无法从时间戳中获取月份。如何从上面的数据集中找到每个月的计数?
我的示例数据集将如下所示,
我相信你可以使用 Tuple2<> 类型
Map<Date, Integer> = myDataSetRDD.map(x -> new Tuple2<Date, Integer>(x.getDate(), 1))
.reduceByKey((x, v) -> x + v)
.collectAsMap();
这样您就可以得到一张地图,其中日期作为键,这些日期的计数作为值。 希望对您有所帮助
考虑到您解释问题的方式:
我尝试使用 withColumn()
创建新的月份列,以便以后可以使用 groupBy()
月份和 count()
。但是我无法从时间戳中获取月份。
您可以使用org.apache.spark.sql.functions
包中提供的静态month()
函数来查找月份,如下所示:
myDataset.withColumn("month", month(col("date"))).groupBy(col("month")).count().show()
其中 col("date")
将具有时间戳(在下面的情况下:"yyyy-mm-dd HH:mm:ss"
)。
使用的输入:
1,2019-04-07 07:24:14,0,8
2,2019-05-07 07:24:14,0,10
5,2019-06-07 07:24:14,0,6
3,2019-04-07 07:24:14,0,7
这将为您提供如下输出:
+-----+-----+
|month|count|
+-----+-----+
| 6| 1|
| 5| 1|
| 4| 2|
+-----+-----+
希望对您有所帮助!!