scala - 检查 arraytype 列是否包含 null

标签 scala apache-spark dataframe null apache-spark-sql

我有一个包含可以包含整数值的数组类型列的数据框。如果没有值,它将只包含一个值,它将是空值
重要 :注意该列不会为空,而是具有单个值的数组;空值

> val df: DataFrame  = Seq(("foo", Seq(Some(2), Some(3))), ("bar", Seq(None))).toDF("k", "v")
df: org.apache.spark.sql.DataFrame = [k: string, v: array<int>]
> df.show()
+---+------+
|  k|     v|
+---+------+
|foo|[2, 3]|
|bar|[null]|
问题 :我想获取具有空值的行。

到目前为止我尝试过的:
> df.filter(array_contains(df("v"), 2)).show()
+---+------+
|  k|     v|
+---+------+
|foo|[2, 3]|
+---+------+
对于 null,它似乎不起作用
> df.filter(array_contains(df("v"), null)).show()

org.apache.spark.sql.AnalysisException: cannot resolve 'array_contains(v, NULL)' due to data type mismatch: Null typed values cannot be used as arguments;


或者
> df.filter(array_contains(df("v"), None)).show()

java.lang.RuntimeException: Unsupported literal type class scala.None$ None

最佳答案

无法使用 array_contains在这种情况下,因为 SQL NULL不能平等比较。

您可以使用 udf像这样:

val contains_null = udf((xs: Seq[Integer]) => xs.contains(null))

df.where(contains_null($"v")).show

// +---+------+
// |  k|     v|
// +---+------+
// |bar|[null]|

关于scala - 检查 arraytype 列是否包含 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44307744/

相关文章:

scala - 如何在Intellij IDEA中运行Spark示例程序

eclipse - 如何让 Eclipse 识别 SBT 的依赖关系

scala - select后的spark sql where子句

apache-spark - foreachBatches 在来自多个 Kafka 主题的流式查询中包含什么?

python - 列上的十分位数 Pandas DataFrame

scala - 使用 State Monad 在 Scala 中进行功能广度优先搜索

python - Spark : Broadcast variables: It appears that you are attempting to reference SparkContext from a broadcast variable, Action ,或转换

scala - Spark Structured Streaming 不会在 Kafka 偏移量处重新启动

apache-spark - 访问 pyspark 数据框中的嵌套列

python - Pandas 连接列