Scala 在Spark中创建自定义项时出错
我正试图使用以下代码在Spark中创建一个UDFScala 在Spark中创建自定义项时出错,scala,apache-spark,user-defined-functions,Scala,Apache Spark,User Defined Functions,我正试图使用以下代码在Spark中创建一个UDF val makeSIfTesla = udf {(make: BigInt) => if(make == 0) 1 else make} 但我得到了以下错误: java.lang.UnsupportedOperationException: Schema for type Any is not supported 为什么?修复如下代码: val makeSIfTesla = udf {(make: BigInt) => if(ma
val makeSIfTesla = udf {(make: BigInt) => if(make == 0) 1 else make}
但我得到了以下错误:
java.lang.UnsupportedOperationException: Schema for type Any is not supported
为什么?修复如下代码:
val makeSIfTesla = udf {(make: BigInt) => if(make == 0) BigInt(1) else make}
问题是1是Int,make是BigInt,因此udf中的方法返回Any。udf函数不支持Any,因此您会看到错误。使类型一致将使方法返回BigInt并修复该问题。您还可以使make的type Int出错,因为您将1作为整数返回。另外,蜂巢中的bigint实际上是一个长的。因此,您的else返回Long,而if返回Int,这使得您的UDF的返回类型成为Spark DataFrame不支持的任何类型 如果您使用df.schema,它将显示您实际需要的是LongType 您的UDF应该类似于:
val makeSIfTesla = udf {(make: Long) => if(make == 0) 1.toLong else make}
//makeSIfTesla : UserDefinedFunction = UserDefinedFunction(<function1>,LongType,List(LongType))
其中x是传递给UDF makeSIfTesla的列。1是整数,make是BigInt。让它们都一样。我改变了密码就像你的答案一样。然后我得到了另一个错误:java.lang.UnsupportedOperationException:scala.math.BigInt类型的模式不是supported@RyanWang-试着换成长的?
val makeSIfTesla = udf {(make: Long) => if(make == 0) 1.toLong else make}
//makeSIfTesla : UserDefinedFunction = UserDefinedFunction(<function1>,LongType,List(LongType))
df.withColumn("x" , when($"x" === lit(0) , lit(1) ).otherwise($"x") )