【问题标题】:How to create a UDF in Spark with a parameter of Timestamp/Date type如何在 Spark 中使用 Timestamp/Date 类型的参数创建 UDF
【发布时间】:2018-08-22 07:02:04
【问题描述】:

我正在尝试使用以下代码在 Spark 2.2 中创建 UDF:

spark.udf.register(
"DAYOFWEEK",
(timestamp: java.sql.Timestamp) => {
  new Timestamp()
  val cal = Calendar.getInstance()
  cal.setTime(timestamp)
  cal.get(Calendar.DAY_OF_WEEK)
}

稍后,当启动下一个 SQL 查询时:

SELECT DAYOFWEEK(now())

出现下一个异常:

cannot resolve 'UDF:DAYOFWEEK(current_timestamp())' due to data type mismatch: argument 1 requires bigint type, however, 'current_timestamp()' is of timestamp type.; line 1 pos 7;

我做错了什么?

【问题讨论】:

  • 你有不同的UDF,它以bigint为参数吗?
  • SELECT DAYOFWEEK(now()) 没有问题。你一定是在传递别的东西

标签: apache-spark apache-spark-sql


【解决方案1】:

@Constantine 感谢您的建议。问题是已经注册了一个同名但使用日期作为参数的 UDF:

udf.register(
  "DAYOFWEEK",
  (date: Date) => {
    val cal = Calendar.getInstance()
    cal.setTime(date)
    cal.get(Calendar.DAY_OF_WEEK)
  }
)

一旦会话只注册了一个 DAYOFWEEK UDF,它就会按预期工作

【讨论】:

    【解决方案2】:
    scala> sqlContext.udf.register(
         | "DAYOFWEEK",
         | (timestamp: java.sql.Timestamp) => {
         |   val cal = Calendar.getInstance()
         |   cal.setTime(timestamp)
         |   cal.get(Calendar.DAY_OF_WEEK)
         | });
    res16: org.apache.spark.sql.UserDefinedFunction = UserDefinedFunction(<function1>,IntegerType,List(TimestampType))
    
    scala> 
    
    scala> val dd = sqlContext.sql("select DAYOFWEEK(now())")
    dd: org.apache.spark.sql.DataFrame = [_c0: int]
    
    
    scala> dd.show
    +---+
    |_c0|
    +---+
    |  4|
    +---+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-29
      • 2015-07-23
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      相关资源
      最近更新 更多