Spark:将数据框的每一行与另一个数据框的所有行连接的方式

时间:2018-08-03 20:00:51

标签: scala apache-spark

假设我具有以下数据框:

val df1 = sc.parallelize(Seq("a1" -> "a2", "b1" -> "b2", "c1" -> "c2")).toDF("a", "b")
val df2 = sc.parallelize(Seq("aa1" -> "aa2", "bb1" -> "bb2")).toDF("aa", "bb")

我想要以下内容:

 | a  | b  | aa  | bb  |
 ----------------------
 | a1 | a2 | aa1 | aa2 |
 | a1 | a2 | bb1 | bb2 |
 | b1 | b2 | aa1 | aa2 |
 | b1 | b2 | bb1 | bb2 |
 | c1 | c2 | aa1 | aa2 |
 | c1 | c2 | bb1 | bb2 |

因此df1的每一行都映射到df2的所有行。我的操作方式如下:

val df1_dummy = df1.withColumn("dummy_df1", lit("dummy"))
val df2_dummy = df2.withColumn("dummy_df2", lit("dummy"))
val desired_result = df1_dummy
                       .join(df2_dummy, $"dummy_df1" === $"dummy_df2", "left")
                       .drop("dummy_df1")
                       .drop("dummy_df2")

它给出了预期的结果,但似乎有点不好。有更有效的方法吗?有什么建议吗?

1 个答案:

答案 0 :(得分:4)

这就是crossJoin的作用:

val result = df1.crossJoin(df2)

result.show()
// +---+---+---+---+
// |a  |b  |aa |bb |
// +---+---+---+---+
// |a1 |a2 |aa1|aa2|
// |a1 |a2 |bb1|bb2|
// |b1 |b2 |aa1|aa2|
// |b1 |b2 |bb1|bb2|
// |c1 |c2 |aa1|aa2|
// |c1 |c2 |bb1|bb2|
// +---+---+---+---+