1. 程式人生 > 其它 >spark讀取巢狀資料

spark讀取巢狀資料

技術標籤:spark大資料

背景:最近,我遇到一種場景,需要從複雜的源資料(含有巢狀欄位)中抽取部分巢狀欄位,經過一番摸索,發現可以通過以下方式來抽取資料。

import org.apache.spark.sql.types._
val schema = new StructType()
.add("typeId", IntegerType)
.add("offsetId", LongType)
.add("data", ArrayType(
	new StructType()
	.add("f1", LongType)
.add("f2", ArrayType( new StructType() .add("f2_1",LongType) .add("f2_2",StringType) )) ) ) spark.read.schema(schema).parquet("/to/path").printSchema

執行結果:
root
|-- typeId: integer (nullable = true)
|-- offsetId: long (nullable = true)
|-- data: array (nullable = true)

| |-- element: struct (containsNull = true)
| | |-- f1: long (nullable = true)
| | |-- f2: array (nullable = true)
| | | |-- element: struct (containsNull = true)
| | | | |-- f2_1: long (nullable = true)
| | | | |-- f2_2: string (nullable = true)