如果你真的需要使用你的函数,我可以建议两个选项:
1) 使用地图/toDF:
import org.apache.spark.sql.Row
import sqlContext.implicits._
def getTimestamp: (String => java.sql.Timestamp) = // your function here
val test = myDF.select("my_column").rdd.map {
case Row(string_val: String) => (string_val, getTimestamp(string_val))
}.toDF("my_column", "new_column")
2) 使用 UDF (UserDefinedFunction):
import org.apache.spark.sql.functions._
def getTimestamp: (String => java.sql.Timestamp) = // your function here
val newCol = udf(getTimestamp).apply(col("my_column")) // creates the new column
val test = myDF.withColumn("new_column", newCol) // adds the new column to original DF
this nice article by Bill Chambers 中有更多关于 Spark SQL UDF 的详细信息。
或者,
如果您只想将 StringType 列转换为 TimestampType 列,您可以使用自 Spark SQL 1.5 起提供的 unix_timestamp column function:
val test = myDF
.withColumn("new_column", unix_timestamp(col("my_column"), "yyyy-MM-dd HH:mm").cast("timestamp"))
注意:对于 spark 1.5.x,需要在转换为时间戳之前将 unix_timestamp 的结果乘以 1000(问题 SPARK-11724)。结果代码将是:
val test = myDF
.withColumn("new_column", (unix_timestamp(col("my_column"), "yyyy-MM-dd HH:mm") *1000L).cast("timestamp"))
编辑:添加 udf 选项