我想动态地在多个列上加入两个spark-scala数据帧。我将避免硬编码列名称比较,如以下声明中所示;
val joinRes = df1.join(df2, df1("col1") == df2("col1") and df1("col2") == df2("col2"))
此查询的解决方案已存在于pyspark版本中 - 在以下链接中提供 PySpark DataFrame - Join on multiple columns dynamically
我想使用spark-scala
编写相同的代码答案 0 :(得分:8)
在scala中,你可以像在python中一样使用它,但是你需要使用map和reduce函数:
val sparkSession = SparkSession.builder().getOrCreate()
import sparkSession.implicits._
val df1 = List("a,b", "b,c", "c,d").toDF("col1","col2")
val df2 = List("1,2", "2,c", "3,4").toDF("col1","col2")
val columnsdf1 = df1.columns
val columnsdf2 = df2.columns
val joinExprs = columnsdf1
.zip(columnsdf2)
.map{case (c1, c2) => df1(c1) === df2(c2)}
.reduce(_ && _)
val dfJoinRes = df1.join(df2,joinExprs)