如何处理原始可为空类型的Spark UDF输入/输出 [英] How to deal with Spark UDF input/output of primitive nullable type

查看:163
本文介绍了如何处理原始可为空类型的Spark UDF输入/输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

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

1) Spark doesn't call UDF if input is column of primitive type that contains null:

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)无法从UDF生成null作为原始类型的列:

2) Can't produce null from UDF as a column of primitive type:

udf { (x: String) => null: Double } // compile error

推荐答案

相应于

请注意,如果您使用原始参数,则无法检查 如果它为null,则UDF将为您返回null. 基本输入为null. 使用框式或[[选项]](如果您想这样做) 自己处理null.

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作为原始类型的列:


So, the easiest solution is just to use boxed types if your UDF input is nullable column of primitive type OR/AND you need to output null from UDF as a column of primitive type:

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|
+-----+-----+

这篇关于如何处理原始可为空类型的Spark UDF输入/输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆