dat*_*pug 5 apache-spark apache-spark-sql
Spark 2.4引入了新的有用的涉及数组的Spark SQL函数,但是当我发现:select array_remove(array(1, 2, 3, null, 3), null)
is null
和not 的结果时,我有点困惑
[1, 2, 3, 3].
这是预期的行为吗?是否可以使用删除空值array_remove
?
附带说明一下,目前我正在使用的替代方法是databricks中的高阶函数:
select filter(array(1, 2, 3, null, 3), x -> x is not null)
Sar*_*ema 13
回答你的第一个问题,这是预期的行为吗?, 是的。因为官方笔记本(https://docs.databricks.com/_static/notebooks/apache-spark-2.4-functions.html)指出“从给定数组中删除与给定元素相等的所有元素”。并
NULL
对应于未定义的值 & 结果也未定义。
所以,我认为NULL
s 超出了这个功能的范围。
最好你找到一种方法来克服这个问题,你也可以使用,spark.sql("""SELECT array_except(array(1, 2, 3, 3, null, 3, 3,3, 4, 5), array(null))""").show()
但缺点是结果不会重复。
Zyg*_*ygD 11
火花3.4+
array_compact("col_name")
Run Code Online (Sandbox Code Playgroud)
完整的 PySpark 示例:
from pyspark.sql import functions as F
df = spark.createDataFrame([([3, None, 3],)], ["c"])
df.show()
# +------------+
# | c|
# +------------+
# |[3, null, 3]|
# +------------+
df = df.withColumn("c", F.array_compact("c"))
df.show()
# +------+
# | c|
# +------+
# |[3, 3]|
# +------+
Run Code Online (Sandbox Code Playgroud)
你可以在 Spark 2 中做这样的事情:
import org.apache.spark.sql.functions._
import org.apache.spark.sql._
/**
* Array without nulls
* For complex types, you are responsible for passing in a nullPlaceholder of the same type as elements in the array
*/
def non_null_array(columns: Seq[Column], nullPlaceholder: Any = "???? ?? ???"): Column =
array_remove(array(columns.map(c => coalesce(c, lit(nullPlaceholder))): _*), nullPlaceholder)
Run Code Online (Sandbox Code Playgroud)
在 Spark 3 中,有新的数组过滤功能,您可以执行以下操作:
df.select(filter(col("array_column"), x => x.isNotNull))
Run Code Online (Sandbox Code Playgroud)
https://docs.databricks.com/_static/notebooks/apache-spark-2.4-functions.html
array_remove(array, T): array 从给定数组中移除所有等于给定元素的元素。
注意:我只参考了文档,他们采用了相同的数据。**null 永远不能等于 null。