添加带有一个when子句的多列



我有一个代码看起来像这样:

df.withColumn( colPath , when( col(colType) =!= S_IFLNK_name, regexp_extract(col(tempColPath) , exp = "^(.*\/).*$", groupIdx = 1 ) )
.otherwise( regexp_extract( col(tempColPath), exp = "^(.*\/)(?:[^\/]+\-\>.*)$", groupIdx = 1 ) ) )
.withColumn( colFilename, when( col(colType) =!= S_IFLNK_name, regexp_extract(col(tempColPath), exp = "^(?:.*\/)(.*)$", groupIdx = 1 ) )
.otherwise( regexp_extract( col(tempColPath), exp = "^(?:.*\/)([^\/]+\-\>.*)$", groupIdx = 1 ) ) )

不需要理解该代码,但我在这里的目标是能够只使用一个when子句并同时添加两列
做两次这个测试来添加一列是一个可怕的性能问题,有可能吗
我尝试使用match case,但您无法将它们应用于Columns值。

来自withColumn的spark文档:(https://spark.apache.org/docs/2.4.4/api/java/org/apache/spark/sql/Dataset.html#withColumn-java.lang.String-org.apache.spark.sql.Column-(:

通过添加列或替换具有相同名称的现有列来返回新的数据集。

因此,对需要添加的每个新列使用.withColumn

yourDF
.withColumn("new_column",
when($"old_column".isNull, lit("new_column_true_value"))
.otherwise($"new_column_false_value"))
.withColumn("new_column_2",
when($"old_column_2".isNull, lit("new_column_2_true_value"))
.otherwise($"new_column_2_false_value"))

最新更新