首页 > 解决方案 > 我可以在 Spark Dataframe udf 中使用 java.time.LocalDate 吗?

问题描述

我必须调用一个采用java.time.LocalDateas 输入参数的方法。

我在 Spark Dataframe 中做,我在 udf 中调用该方法。

import org.apache.spark.sql.Row
import java.time.format.DateTimeFormatter
import java.time.ZonedDateTime
import java.time.LocalDate

val df = Seq((1, "2018-02-11T09:40:00+08:00")).toDF("id", "date_time")
df.show

+---+-------------------------+
|id |date_time                |
+---+-------------------------+
|1  |2018-02-11T09:40:00+08:00|
+---+-------------------------+

def formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME
val dateTime = "2018-06-10T09:30:00+02:00"
def complexMethod(d: LocalDate) = {
  d
  // do really complex thing
  // imagine there could be many other input params, localDate is just the one blocking here
}

我尝试这样做:

val transformer = udf((dateTime: String) => {
  val localDate = ZonedDateTime.from(formatter.parse(dateTime)).toLocalDate;
  complexMethod(localDate)
})

df.withColumn("transformed", transformer(col("date_time"))).show

会有错误:

// java.lang.UnsupportedOperationException: Schema for type java.time.LocalDate is not supported

我必须java.time.LocalDate作为输入传递给complexMethod(想象这complexMethod是来自另一个库),并在 udf 中调用它。该错误似乎意味着java.time.LocalDateudf 中不允许这样做。

  1. java.time.LocalDate不允许的原因是什么?
  2. 我怎样才能调用complexMethodudf?
  3. 如果真的不可能,最好的打电话方式是complexMethod什么?使用 RDD,数据集?

标签: apache-sparkapache-spark-sqluser-defined-functionsjava-time

解决方案


推荐阅读