gpt4 book ai didi

sql - 在 Apache Spark Join 中包含空值

转载 作者:太空宇宙 更新时间:2023-11-03 21:47:44 30 4
gpt4 key购买 nike

我想在 Apache Spark 连接中包含空值。默认情况下,Spark 不包含带有 null 的行。

这是默认的 Spark 行为。

val numbersDf = Seq(
("123"),
("456"),
(null),
("")
).toDF("numbers")

val lettersDf = Seq(
("123", "abc"),
("456", "def"),
(null, "zzz"),
("", "hhh")
).toDF("numbers", "letters")

val joinedDf = numbersDf.join(lettersDf, Seq("numbers"))

这是joinedDf.show()的输出:

+-------+-------+
|numbers|letters|
+-------+-------+
| 123| abc|
| 456| def|
| | hhh|
+-------+-------+

这是我想要的输出:

+-------+-------+
|numbers|letters|
+-------+-------+
| 123| abc|
| 456| def|
| | hhh|
| null| zzz|
+-------+-------+

最佳答案

Spark提供了一个特殊的NULL安全相等运算符:

numbersDf
.join(lettersDf, numbersDf("numbers") <=> lettersDf("numbers"))
.drop(lettersDf("numbers"))
+-------+-------+
|numbers|letters|
+-------+-------+
| 123| abc|
| 456| def|
| null| zzz|
| | hhh|
+-------+-------+

请注意不要将其与 Spark 1.5 或更早版本一起使用。在 Spark 1.6 之前,它需要笛卡尔积( SPARK-11111 - 快速空安全连接)。

Spark 2.3.0 或更高版本中,您可以在 PySpark 中使用 Column.eqNullSafe:

numbers_df = sc.parallelize([
("123", ), ("456", ), (None, ), ("", )
]).toDF(["numbers"])

letters_df = sc.parallelize([
("123", "abc"), ("456", "def"), (None, "zzz"), ("", "hhh")
]).toDF(["numbers", "letters"])

numbers_df.join(letters_df, numbers_df.numbers.eqNullSafe(letters_df.numbers))
+-------+-------+-------+
|numbers|numbers|letters|
+-------+-------+-------+
| 456| 456| def|
| null| null| zzz|
| | | hhh|
| 123| 123| abc|
+-------+-------+-------+

SparkR中的%<=>%:

numbers_df <- createDataFrame(data.frame(numbers = c("123", "456", NA, "")))
letters_df <- createDataFrame(data.frame(
numbers = c("123", "456", NA, ""),
letters = c("abc", "def", "zzz", "hhh")
))

head(join(numbers_df, letters_df, numbers_df$numbers %<=>% letters_df$numbers))
  numbers numbers letters
1 456 456 def
2 <NA> <NA> zzz
3 hhh
4 123 123 abc

通过 SQL (Spark 2.2.0+),您可以使用 IS NOT DISTINCT FROM :

SELECT * FROM numbers JOIN letters 
ON numbers.numbers IS NOT DISTINCT FROM letters.numbers

这也可以与 DataFrame API 一起使用:

numbersDf.alias("numbers")
.join(lettersDf.alias("letters"))
.where("numbers.numbers IS NOT DISTINCT FROM letters.numbers")

关于sql - 在 Apache Spark Join 中包含空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52362068/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com