如何处理列名称中的空白以在expr方法中使用spark合并功能

时间:2019-04-16 11:31:15

标签: apache-spark

我正在我的项目中使用spark coalesce功能。代码在没有空格的列上可以正常工作,但在有间隔的列上无法运行。

e1.csv

id,code,type,no root
1,,A,1
2,,,0
3,123,I,1

e2.csv

id,code,type,no root
1,456,A,1
2,789,A1,0
3,,C,0

逻辑代码

Dataset<Row> df1 = spark.read().format("csv").option("header", "true").load("/home/user/Videos/<folder>/e1.csv");

        Dataset<Row> df2 = spark.read().format("csv").option("header", "true").load("/home/user/Videos/<folder>/e2.csv");


Dataset<Row> newDS = df1.as("a").join(df2.as("b")).where("a.id== b.id").selectExpr("coalesce(`a.no root`,`b.no root`) AS `a.no root`");

newDS.show();


我尝试过的

Dataset<Row> newDS = df1.as("a").join(df2.as("b")).where("a.id== b.id").selectExpr("""coalesce(`a.no root`,`b.no root`) AS `a.no root`""");

结果将是

no root
1
0
1

1 个答案:

答案 0 :(得分:0)

使用以下条件

val newDS = df1.as("a").join(df2.as("b")).where("a.id==b.id").selectExpr("coalesce(a.`no root`,b.`no root`) AS `a.no root`")

将产生预期的输出

+---------+
|a.no root|
+---------+
|        1|
|        0|
|        1|
+---------+