[英]How to use non udf method in Spark?
我的代码如下
myDF.map{ x =>
val inp = MyUtils.doSomething(x.value) //accepts Int values and return Int
MyInfo(inp)
}
这里 MyUtils.doSomething 在我的 spark MyUtils.doSomething
代码中是正常的 function (non UDF)
。 它工作正常
但是当我这样做时
val DF = myDF.withColumn("value", lit(MyUtils.doSomething(col("value").asInstanceOf[Int].toInt)))
为什么它显示错误
class org.apache.spark.sql.Column cannot be cast to class java.lang.Integer
我怎样才能解决这个问题? 有什么方法可以获得col("value")
的基础值,以便我可以在我的doSomething
function 中使用它。
不知道为什么col("value").asInstanceOf[Int].toInt
它没有给出 Int 值?
不知道为什么 col("value").asInstanceOf[Int].toInt 它没有给出 Int 值?
好吧,因为您想如何转换Column("colName", 21, false)
? asInstanceOf
基本上会使编译器忽略这样一个事实,即Column
类型的 object 是 integer,而您将在运行时面临异常。 您应该以一种甚至不需要asInstanceOf
的方式编写代码。 关于您的第一个考虑, UDF
基本上是一个 function,由 spark 序列化为 spark 从站并在列上执行,因此您必须这样做:
import org.apache.spark.sql.functions._
val doSomethingUdf = udf(MyUtils.doSomething)
// if doSomething is defined as a method "def doSomething ..."
// then it would be better to do
// udf(MyUtils.doSomething _)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.