【问题标题】:Spark scala full join outputs null on joining columnSpark scala 完全连接在连接列上输出 null
【发布时间】:2020-01-16 19:50:14
【问题描述】:

我正在尝试将 2 个具有相同列名的数据框组合起来,以创建一个更大的新数据框,同时保留所有数据。如果存在相同的 id,我使用合并来替换一个数据帧中的值。

连接和合并结果很好,但是当 id 存在时,连接列(“id”)会产生 null 值。不知道为什么:

例子:

val tmp = Seq(
  (1,"A"),
  (2,"B"),
  (3,"A"),
  (4,"A")
).toDF("id","label")


val tmp2 = Seq(
  (1,"B"),
  (2,"B"),
  (3,"B"),
  (5, "A")
).toDF("id","label")

代码:

import org.apache.spark.sql.functions._

// replace values in tmp(label) with tmp2(label) if both have same id.
val tmp3 = tmp.join(tmp2, tmp("id") === tmp2("id"), "fullouter")
           .select(tmp("id"), coalesce(tmp2("label"), tmp("label")))

output:
+----+----------------------+
|  id|coalesce(label, label)|
+----+----------------------+
|null|                     A|
|   1|                     B|
|   2|                     B|
|   3|                     B|
|   4|                     A|
+----+----------------------+

通缉:

output:
+----+----------------------+
|  id|coalesce(label, label)|
+----+----------------------+
|   5|                     A|
|   1|                     B|
|   2|                     B|
|   3|                     B|
|   4|                     A|
+----+----------------------+

将连接更改为"full" 我们的"outer" 具有相同的结果。

【问题讨论】:

    标签: scala apache-spark apache-spark-sql outer-join


    【解决方案1】:

    您正在执行完全外连接,因此它将合并两个表中的所有行。

    由于您使用来自tmpid 作为结果ID,当tmp2 中有一行在tmp 中不存在时,它不能采用有效值,因此为空

    要获得预期的输出,您可以在第一列中使用另一个 coalesce,与在第二列中所做的相同

    val tmp3 = tmp.join(tmp2, tmp("id") === tmp2("id"), "fullouter")
    .select(coalesce(tmp("id"), tmp2("id")), coalesce(tmp2("label"), tmp("label")))
    +----------------+----------------------+
    |coalesce(id, id)|coalesce(label, label)|
    +----------------+----------------------+
    |               1|                     B|
    |               3|                     B|
    |               5|                     A|
    |               4|                     A|
    |               2|                     B|
    +----------------+----------------------+
    

    【讨论】:

      猜你喜欢
      • 2017-04-10
      • 1970-01-01
      • 2021-03-22
      • 2020-09-01
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2014-03-01
      相关资源
      最近更新 更多