给出以下示例:
import org.apache.spark.sql.expressions.UserDefinedFunction
import org.apache.spark.sql.functions._
val testUdf: UserDefinedFunction = udf((a: String, b: String, c: Int) => {
val out = s"test1: $a $b $c"
println(out)
out
})
val testUdf2: UserDefinedFunction = udf((a: String, b: String, c: String) => {
val out = s"test2: $a $b $c"
println(out)
out
})
Seq(("hello", "world", null))
.toDF("a", "b", "c")
.withColumn("c", $"c" cast "Int")
.withColumn("test1", testUdf($"a", $"b", $"c"))
.withColumn("test2", testUdf2($"a", $"b", $"c"))
.show
testUdf
似乎没有被调用。没有错误,没有警告,它只返回null。
有没有办法检测这些无声故障?还有,这是怎么回事?
火花2.4.4 Scala 2.11
答案 0 :(得分:5)
标量类型“ Int”不允许为空。变量“ c”类型可以更改为“整数”。
答案 1 :(得分:1)
我不知道是什么原因造成的。但是我认为这很可能是由于隐式转换
代码1
val spark = SparkSession.builder()
.master("local")
.appName("test")
.getOrCreate()
import spark.implicits._
val testUdf: UserDefinedFunction = udf((a: String, b: String, c: Int) => {
val out = s"test1: $a $b $c"
println(out)
out
})
Seq(("hello", "world", null))
.toDF("a", "b", "c")
.withColumn("test1", testUdf($"a", $"b", $"c"))
.show
代码2
val spark = SparkSession.builder()
.master("local")
.appName("test")
.getOrCreate()
import spark.implicits._
val testUdf: UserDefinedFunction = udf((a: String, b: String, c: String) => {
val out = s"test1: $a $b $c"
println(out)
out
})
Seq(("hello", "world", null))
.toDF("a", "b", "c")
.withColumn("test1", testUdf($"a", $"b", $"c"))
.show
代码1逻辑计划
代码2逻辑计划
答案 2 :(得分:0)
当您尝试将其强制转换为null时,您应该会遇到一个scala.MatchError: scala.Null
错误,此外您对UDF的定义对我不起作用,因为我在尝试注册时得到了一个java.lang.UnsupportedOperationException: Schema for type AnyRef is not supported
。>
那呢:
import org.apache.spark.sql.expressions.UserDefinedFunction
import org.apache.spark.sql.functions._
def testUdf(a: String, b: String, c: Integer): String = {
val out = s"test1: $a $b $c"
println(out)
out
}
def testUdf2(a: String, b: String, c: String): String = {
val out = s"test2: $a $b $c"
println(out)
out
}
val yourTestUDF = udf(testUdf _)
val yourTestUDF2 = udf(testUdf2 _)
// spark.udf.register("yourTestUDF", yourTestUDF) // just in case you need it in SQL
spark.createDataFrame(Seq(("hello", "world", null.asInstanceOf[Integer])))
.toDF("a", "b", "c")
.withColumn("test1", yourTestUDF($"a", $"b", $"c"))
.withColumn("test2", yourTestUDF2($"a", $"b", $"c"))
.show(false)
输出:
test1: hello world null
test2: hello world null
+-----+-----+----+-----------------------+-----------------------+
|a |b |c |test1 |test2 |
+-----+-----+----+-----------------------+-----------------------+
|hello|world|null|test1: hello world null|test2: hello world null|
+-----+-----+----+-----------------------+-----------------------+