[英]Converting nested ArrayType of String to Nested ArrayType of date using UDF spark
輸入 :
f1 : [["2017-08-08","2017/08/08"],["2017-08-08","2017/08/08"]]
f1的架構: ArrayType(ArrayType(StringType))
我想使用Spark UDF將日期值從String轉換為日期格式。 這里輸入可能具有Array[Any]
。 我已經寫過["2017-08-07","2013/08/02"]
它適用於像["2017-08-07","2013/08/02"]
類的一維值。 對於一維,我的udf將是:
def toDateFormatUdf(dateFormat:String) = udf(( dateValue: mutable.WrappedArray[_]) => dateValue match{
case null => null
case datevalue: mutable.WrappedArray[String] => datevalue.map(date => new java.sql.Date(new SimpleDateFormat(dateFormat).parse(String.valueOf(date)).getTime))
})
我嘗試將Seq[Row]
類型作為UDF參數,但無法形成邏輯。 有什么方法可以在Scala中為多維數組實現UDF?
如果數據有一致的格式,你可以cast
,但在這里它會排除yyyy/MM/dd
記錄:
val df = Seq((1L, Seq(Seq("2017-08-08", "2017/08/08"), Seq("2017-08-08","2017/08/08")))).toDF("id", "dates")
df.select($"dates".cast("array<array<date>>")).show(1, false)
+----------------------------------------------------------------+
|dates |
+----------------------------------------------------------------+
|[WrappedArray(2017-08-08, null), WrappedArray(2017-08-08, null)]|
+----------------------------------------------------------------+
在這里,我只重寫格式:
val f1 = "(^[0-9]{4})-([0-9]{2})-([0-9]{2})$".r
val f2 = "(^[0-9]{4})/([0-9]{2})/([0-9]{2})$".r
val reformat = udf((xxs: Seq[Seq[String]]) => xxs match {
case null => null
case xxs => xxs.map {
case null => null
case xs => xs.map { x=> {
x match {
case null => null
case f1(_, _, _) => x
case f2(year, month, day) => s"${year}-${month}-${day}"
case _ => null
}
}}
}
})
然后投
df.select(reformat($"dates")).show(1, false)
+----------------------------------------------------------------------------+
|UDF(dates) |
+----------------------------------------------------------------------------+
|[WrappedArray(2017-08-08, 2017-08-08), WrappedArray(2017-08-08, 2017-08-08)]|
+----------------------------------------------------------------------------+
避免不必要的SimpleDateFormat
初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.