如何使用 Java 在 Spark SQL 的 DataFrame 中进行 "col(a)==null? col(b) : col(c)" 列操作?

How to do "col(a)==null? col(b) : col(c)" column operation in Spark SQL's DataFrame using Java?

我必须在机器学习之前做一些数据清理,我的数据框如下所示:

+-------+--------+---------+--------+-------+
| userid|artistid|playcount|   badid| goodid|
+-------+--------+---------+--------+-------+
|2158448|10006467|        1|10006467|1244705|
|2144107|10009022|        5|10009022|1024524|
|1006831|10009473|        1|10009473|1010373|
|2011584|10016312|       13|10016312|1000127|
|2052189|10021776|        2|10021776|1082784|
|2052189|10022667|        1|10022667|1082784|
|1060325|10039984|        1|10039984|1001463|
|2077268|10043655|        1|10043655|1000597|
|1038421|10048281|        2|10048281|1256384|
|2116983|10055238|        1|10055238|1003509|
|2211143|10055238|       27|10055238|1003509|
|1000083| 1006162|        2| 1006162|1048788|
|1001371| 1006162|        1| 1006162|1048788|
|1001411| 1006162|        1| 1006162|1048788|
|1002138| 1006162|        3| 1006162|1048788|
|1009943| 1006162|        2| 1006162|1048788|
|1021747| 1006162|        4| 1006162|1048788|
|1031726| 1006162|        1| 1006162|1048788|
|1032062| 1006162|        2| 1006162|1048788|
|1036948| 1006162|        1| 1006162|1048788|
+-------+--------+---------+--------+-------+

我需要生成一个包含当前所有列的新 DataFrame,并在 Java 中添加一个新列。这个新的"Column"的逻辑是这样的:

IsNull(Col('badid')) ? Col('artistid') : Col('goodid')

有什么建议吗?

您可以使用 when / otherwise:

when(col("badid").isNull(), col("artistid")).otherwise(col("goodid"))

相当于SQL CASE WHEN ... ELSE:

CASE  
    WHEN badid IS NULL THEN artistid
    ELSE goodid
END