[英]How to get the field names situated in a ArrayType Column
這是我的架構
root
|-- tags: array (nullable = true)
| |-- element: array (containsNull = true)
| | |-- element: struct (containsNull = true)
| | | |-- context: string (nullable = true)
| | | |-- key: string (nullable = true)
我想獲取元素上下文和鍵的名稱,並將這些變量的數據類型更改為數組。
當我嘗試使用map獲取字段時,它顯示的是這樣的內容。
arraydf.schema.fields.map(field1 =>
println("FIELDS: "+field1)
Output:
FIELDS:StructField(tags,ArrayType(ArrayType(StructType(StructField(context,StringType,true), StructField(key,StringType,true)),true),true),true)
我希望我的架構是這樣的,無論結構類型下的元素應該是arrayType,我想要一種通用的方式。 請幫我。
root
|-- tags: array (nullable = true)
| |-- element: array (containsNull = true)
| | |-- element: struct (containsNull = true)
| | | |-- context: array (nullable = true)
| | | |-- key: array (nullable = true)
結構上的圖案匹配
import org.apache.spark.sql.types._
import org.apache.spark.sql.DataFrame
def fields(df: DataFrame, c: String) = df.schema(c) match{
case StructField(_, ArrayType(ArrayType(ss: StructType, _), _), _, _) =>
ss.fields map { s =>
(s.name, s.dataType)
}
}
例:
scala> fields(Seq(Seq(Seq((1, 2)))).toDF, "value")
res7: Array[(String, org.apache.spark.sql.types.DataType)] = Array((_1,IntegerType), (_2,IntegerType))
從我得到的結果中,您只想訪問一個元素對嗎? 這通過StructType的點符號和ArrayType的getItem(或僅使用方括號[])來完成。
因此,如果您想擁有這些值,請說一下,嘗試:
arraydf.select("tags[0][0].context, tags[0][0].key")
我建議您也查看explode()函數,這可能會很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.