【发布时间】:2020-05-23 11:24:28
【问题描述】:
我正在使用 spark-sql-2.3.1v 并且有以下场景:
给定一个数据集:
val ds = Seq(
(1, "x1", "y1", "0.1992019"),
(2, null, "y2", "2.2500000"),
(3, "x3", null, "15.34567"),
(4, null, "y4", null),
(5, "x4", "y4", "0")
).toDF("id","col_x", "col_y","value")
即
+---+-----+-----+---------+
| id|col_x|col_y| value|
+---+-----+-----+---------+
| 1| x1| y1|0.1992019|
| 2| null| y2|2.2500000|
| 3| x3| null| 15.34567|
| 4| null| y4| null|
| 5| x4| y4| 0|
+---+-----+-----+---------+
要求:
我得到了需要从外部执行一些计算的操作列(即operationCol)。
在对“col_x”列执行某些操作时,我需要通过过滤掉所有具有“col_x”空值的记录并返回该新数据集来创建一个新数据集。
同样,在对“col_y”列执行一些操作时,我需要通过过滤掉所有具有“col_y”空值的记录并返回该新数据集来创建一个新数据集。
示例:
val operationCol ="col_x";
if(operationCol === "col_x"){
//filter out all rows which has "col_x" null and return that new dataset.
}
if(operationCol === "col_y"){
//filter out all rows which has "col_y" null and return that new dataset.
}
当 operationCol === "col_x" 预期输出时:
+---+-----+-----+---------+
| id|col_x|col_y| value|
+---+-----+-----+---------+
| 1| x1| y1|0.1992019|
| 3| x3| null| 15.34567|
| 5| x4| y4| 0|
+---+-----+-----+---------+
当 operationCol === "col_y" 预期输出时:
+---+-----+-----+---------+
| id|col_x|col_y| value|
+---+-----+-----+---------+
| 1| x1| y1|0.1992019|
| 2| null| y2|2.2500000|
| 4| null| y4| null|
| 5| x4| y4| 0|
+---+-----+-----+---------+
如何实现这个预期的输出? 换句话说,如何进行数据帧的分支?如何在流程中间创建新的数据框/数据集?
【问题讨论】:
标签: apache-spark apache-spark-sql spark-streaming