gpt4 book ai didi

sql - 如何处理原始可空类型的 Spark UDF 输入/输出

转载 作者:行者123 更新时间:2023-12-05 00:14:19 24 4
gpt4 key购买 nike

问题:

1) 如果输入是包含 null 的原始类型列,Spark 不会调用 UDF :

inputDF.show()

+-----+
| x |
+-----+
| null|
| 1.0|
+-----+

inputDF
.withColumn("y",
udf { (x: Double) => 2.0 }.apply($"x") // will not be invoked if $"x" == null
)
.show()

+-----+-----+
| x | y |
+-----+-----+
| null| null|
| 1.0| 2.0|
+-----+-----+

2) 不能生产 null从 UDF 作为原始类型的列:
udf { (x: String) => null: Double } // compile error

最佳答案

据此the docs :

Note that if you use primitive parameters, you are not able to check if it is null or not, and the UDF will return null for you if the primitive input is null. Use boxed type or [[Option]] if you wanna do the null-handling yourself.



所以,最简单的解决方案就是使用
盒装类型,如果您的 UDF 输入是原始类型的可为空列
OR/AND 您需要从 UDF 输出 null 作为原始类型的列:
inputDF
.withColumn("y",
udf { (x: java.lang.Double) =>
(if (x == null) 1 else null): java.lang.Integer
}.apply($"x")
)
.show()

+-----+-----+
| x | y |
+-----+-----+
| null| null|
| 1.0| 2.0|
+-----+-----+

关于sql - 如何处理原始可空类型的 Spark UDF 输入/输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42791912/

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