2017-09-18 43 views
-1

我写一个星火斯卡拉UDF,面向“java.lang.UnsupportedOperationException:类型模式中的任何不支持”星火据帧UDF - 模式类型的任何不支持

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"} 
}) 

此抛出错误“ java.lang.UnsupportedOperationException:类型模式中的任何不支持”

+0

你需要一个'else'了。如果没有满足这些条件会怎么样? – philantrovert

回答

2

正如this link disussed你的UDF应该返回:

  • 原语(智力,字符串,布尔值,...)其他支持的类型
  • 列表,数组,其他支持类型的地图
  • 其他支持的类型

所以,如果你添加其他别的代码的case类

  • 元组,编译会成功。

    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 { 
         "" 
        } 
        }) 
    

    你也可以使用模式匹配重新分配你的代码:

    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 _ => "" 
    }