org.apache.spark.SparkException:无法执行用户定义的函数

Inn*_*nna 5 scala nullpointerexception apache-spark apache-spark-sql

我是scala新手,我正在尝试执行以下代码:

val SetID = udf{(c:String, d: String) =>
    if( c.UpperCase.contains("EXKLUS") == true)
    {d}
    else {""}
}
val ParquetWithID = STG1
  .withColumn("ID", SetID( col("line_item"), col("line_item_ID")))
Run Code Online (Sandbox Code Playgroud)

两列 (line_item和) 均按架构中的方式line_item_id定义。StringsSTG1

当我尝试运行代码时出现以下错误:

`org.apache.spark.SparkException: Failed to execute user defined function($anonfun$1$$anonfun$2: (string, string) => string)
at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:370)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$4.apply(SparkPlan.scala:246)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$4.apply(SparkPlan.scala:240)
at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:803)
at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:803)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70)
at org.apache.spark.scheduler.Task.run(Task.scala:86)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Run Code Online (Sandbox Code Playgroud)

Caused by: java.lang.NullPointerException
    at MyTests$$anonfun$1$$anonfun$2.apply(MyTests.scala:356)
    at MyTests$$anonfun$1$$anonfun$2.apply(MyTests.scala:355)
    ... 16 more
Run Code Online (Sandbox Code Playgroud)

我也尝试过c.UpperCase().contains("EXKLUS"),但遇到了同样的错误。但是,如果我只是运行一个“ if equals”语句,一切都会正常。所以我猜问题出UpperCase().contains(" ")在我的函数中,udf但我不明白问题来自哪里。任何帮助将不胜感激!

Ram*_*jan 6

如果schema包含为

 |-- line_item: string (nullable = true)
 |-- line_item_ID: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)

然后在 if 语句中检查null应该解决问题(请注意,有toUpperCase用于字符串的方法)

val SetID = udf{(c:String, d: String) =>
  if(c != null && c.toUpperCase.contains("EXKLUS") == true)
  {d}
  else {""}
}
val ParquetWithID = STG1
  .withColumn("ID", SetID( col("line_item"), col("line_item_ID")))
Run Code Online (Sandbox Code Playgroud)

我希望答案有帮助