2017-03-07 93 views
0

我想寫一個UDF將時間戳轉換爲表示一週小時的整數。我很容易用SparkSql來完成這件事。火花UDF類型不匹配錯誤

enter image description here

我有很多的UDF在我們這個確切的語法的代碼,但此人試圖類型不匹配錯誤。我也試着用col("session_ts_start")來調用我的UDF,但那也失敗了。

import spark.implicits._ 
import java.sql.Timestamp 
import org.apache.spark.sql.functions._ 

def getHourOfWeek() = udf(
    (ts: Timestamp) => unix_timestamp(ts) 
) 

val dDF = df.withColumn("hour", getHourOfWeek()(df("session_ts_start"))) 
dDF.show() 

<console>:154: error: type mismatch; 
found : java.sql.Timestamp 
required: org.apache.spark.sql.Column 
      (ts: Timestamp) => unix_timestamp(ts) 

回答

0

unix_timestamp是一個SQL函數。它operates on Columns不是外在價值:

def unix_timestamp(s: Column): Column 

,它不能在UDF中使用。

我想(...)的時間戳轉換成表示一週的時間整數

import org.apache.spark.sql.Column 
import org.apache.spark.sql.functions.{date_format, hour} 

def getHourOfWeek(c: Column) = 
    // https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html 
    (date_format(c, "u").cast("integer") - 1) * 24 + hour(c) 

val df = Seq("2017-03-07 01:00:00").toDF("ts").select($"ts".cast("timestamp")) 

df.select(getHourOfWeek($"ts").alias("hour")).show 
+----+ 
|hour| 
+----+ 
| 25| 
+----+ 

另一種可能的解決方案:

import org.apache.spark.sql.functions.{next_day, date_sub} 

def getHourOfWeek2(c: Column) = ((
    c.cast("bigint") - 
    date_sub(next_day(c, "Mon"), 7).cast("timestamp").cast("bigint") 
)/3600).cast("int") 

df.select(getHourOfWeek2($"ts").alias("hour")) 
+----+ 
|hour| 
+----+ 
| 25| 
+----+ 

注意:這兩個解決方案都不處理夏令時或其他日期/時間微妙之處。