我有一個具有如下架構的資料框
root
|-- date: timestamp (nullable = true)
|-- questionAnswerList: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- questionNumber: string (nullable = true)
| | |-- listAnswers: array (nullable = true)
| | | |-- element: string(containsNull = true)
我想在結構陣列中添加一個新欄位,如下圖所示
root
|-- date: timestamp (nullable = true)
|-- questionAnswerList: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- index: integer (nullable = true)
| | |-- questionNumber: string (nullable = true)
| | |-- listAnswers: array (nullable = true)
| | | |-- element: string(containsNull = true)
我嘗試使用如下所示的 UDF
val addIndexInStruct: UserDefinedFunction = udf((data: Seq[Row]) => {
data.zipWithIndex.map{case (Row(x:String,y:Array[String]), index) => (index, x, y )}
})
df.withColumn("newCol",addIndexInStruct($"questionAnswerList")).show(false)
但我有以下錯誤:
Caused by: scala.MatchError: ([Q10,WrappedArray(R10.1, R10.2)],0) (of class scala.Tuple2)
有人知道如何在 spark 2.X 中執行此操作嗎?我在別人的帖子里看到,在spark 3.X中,可以使用transform函式
uj5u.com熱心網友回復:
我終于解決了。在模式匹配部分必須使用 Seq 而不是 Array
val addIndexInStruct: UserDefinedFunction = udf((data: Seq[Row]) => {
data.zipWithIndex.map{case (Row(x: String,y: Seq[String]), index) => (index, x, y )}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537492.html
標籤:阿帕奇火花用户定义函数
上一篇:Pyspark掉落的專欄沒有消失
