简体   繁体   English

Spark Dataframe UDF - 不支持 Any 类型的架构

[英]Spark Dataframe UDF - Schema for type Any is not supported

I am writing a Spark Scala UDF and facing "java.lang.UnsupportedOperationException: Schema for type Any is not supported"我正在编写 Spark Scala UDF 并面临“java.lang.UnsupportedOperationException:不支持任何类型的架构”

import org.apache.spark.sql.expressions.UserDefinedFunction
import org.apache.spark.sql.functions.udf

val aBP = udf((bG: String, pS: String, bP: String, iOne: String, iTwo: String) => {
  if (bG != "I") {"NA"}
  else if (pS == "D")
    {if (iTwo != null) iOne else "NA"}
  else if (pS == "U")
    {if (bP != null) bP else "NA"}
})

This is throwing error "java.lang.UnsupportedOperationException: Schema for type Any is not supported"这是抛出错误“java.lang.UnsupportedOperationException:不支持任何类型的架构”

As disussed in this link your udf should return:正如在此链接中讨论的那样,您的 udf 应该返回:

  • Primitives (Int, String, Boolean, ...)原语(Int、String、Boolean 等)
  • Tuples of other supported types其他支持类型的元组
  • Lists, Arrays, Maps of other supported types其他支持类型的列表、数组、映射
  • Case Classes of other supported types其他支持类型的案例类

So if you add another else to your code, the compilation will succeed.因此,如果您在代码中添加另一个 else,编译将成功。

  val aBP = udf((bG: String, pS: String, bP: String, iOne: String, iTwo: String) => {
    if (bG != "I") {"NA"}
    else if (pS == "D") {
      if (iTwo != null) 
        iOne 
      else "NA"
    } else if (pS == "U") {
      if (bP != null) 
        bP 
      else 
        "NA"
    } else {
      ""
    }
  })

You could also redistribute your code using pattern matching:您还可以使用模式匹配重新分发您的代码:

val aBP = udf [String, String, String, String, String, String] {
  case (bG: String, _, _, _, _)                       if bG != "I" => "NA"
  case (_, pS: String, _, iOne: String, iTwo: String) if pS == "D" && iTwo.isEmpty => iOne
  case (_, pS: String, _, _, _)                       if pS == "D" => "NA"
  case (_, pS: String, bP: String, _, _)              if pS == "U" && bP.isEmpty => bP
  case (_, pS: String, _, _, _)                       if pS == "U" => "NA"
  case _ => ""
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM