【问题标题】:udf spark Scala return case classudf spark Scala 返回案例类
【发布时间】:2019-12-11 19:33:39
【问题描述】:
import org.apache.spark.sql.functions._

case class oneClass(a : Int , b: String , c :string)

val doSomthing = udf ((t1 : Seq[String], str : String , values : t2 Seq[String])
    => {
    val pos = t1.indexOf(str)
    if (pos >= 0) oneClass(pos, str,t2(pos))
    //if no control of pos possible return -1 ===> indexoutofboundsexception
    //if control the udf return Any then when I use it ===> Exception
    }
)

只有当 pos >= 0 并且一直返回 case class 时,我如何才能返回 case class ??

【问题讨论】:

    标签: scala apache-spark user-defined-functions


    【解决方案1】:

    如果这不应该发生,要么抛出异常(spark 作业将失败):

    val doSomthing = udf ((t1 : Seq[String], str : String , t2 :Seq[String])=> {
      val pos = t1.indexOf(str)
      if (pos >= 0) oneClass(pos, str,t2(pos)) else {
        throw new IllegalArgumentException
      }
    })
    

    否则使用Option:

    val doSomthing = udf ((t1 : Seq[String], str : String , t2 :Seq[String])=> {
      val pos = t1.indexOf(str)
      if (pos >= 0) Some(oneClass(pos, str,t2(pos))) else None
    })
    

    在后一种情况下,您的 DataFrame 中的结果将是 nullNone 转换为 null

    如果没有抛出异常,也可以用于返回结果的模式:

    val doSomthing = udf ((t1 : Seq[String], str : String , t2 :Seq[String])=> {
      scala.util.Try{
      val pos = t1.indexOf(str)
      oneClass(pos, str,t2(pos))
      }.toOption
    })
    

    这对测试很有用,但我不认为这是一种好的做法

    【讨论】:

    • 非常感谢,我需要的是当 pos 为 -1 时不返回任何内容,否则返回 oneClass(pos, str,t2(pos)
    • @K.T.A ??这就是我写的,None 什么都不是……
    猜你喜欢
    • 2017-05-21
    • 2018-09-17
    • 1970-01-01
    • 2018-02-02
    • 2017-11-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多