繁体   English   中英

如何使用java将数据集的两行合并为spark中的一行

[英]How to combine the two rows of a dataset into a single row in spark using java

我正在以 json 格式从 kafka 主题中读取交易。 然后我应用了一些转换来获取基于 txn_status 的聚合。 下面是架构。

root |-- window: struct (nullable = true) | |-- 开始:时间戳(可为空 = 真)| |-- 结束:时间戳(可空 = 真) |-- txn_status:字符串(可空 = 真) |-- 计数:长(可空 = 假)

在对给定窗口应用分组后,我的批处理输出如下所示。 [![在此处输入图像描述][1]][1]

但我想要如下 json 格式的输出。

 { “start_end_time”: “28/12/2018 11:32:00.000”, “count_Total” : 6 “count_RCVD” : 5, “count_FAILED”: 1 } > how to combine two rows in a spark dataset. > > > [1]: https://i.stack.imgur.com/sCJuX.jpg

根据您显示的图像,我创建了一个数据框或临时表,并为您的问题提供了解决方案。

斯卡拉代码:

case class txn_rec(txn_status: String, count: Int, start_end_time: String)

var txDf=sc.parallelize(Array(new txn_rec("FAIL",9,"2019-03-08 016:40:00, 2019-03-08 016:57:00"), 
    new txn_rec("RCVD",161,"2019-03-08 016:40:00, 2019-03-08 016:57:00"))).toDF

txDf.createOrReplaceTempView("temp")

var resDF=spark.sql("select start_end_time, (select sum(count) from temp) as total_count , (select count from temp where txn_status='RCVD') as rcvd_count,(select count from temp where txn_status='FAIL') as failed_count  from temp group by start_end_time")

resDF.show

resDF.toJSON.collectAsList.toString

您可以看到屏幕截图中显示的输出。

输出-1

输出-2

暂无
暂无

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

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