如何将大结构列添加到数据框

How to add large struct column to dataframe

我想向数据框添加一个结构列,但该结构有超过 100 个字段。
我了解到 case class 可以更改为 struct 列,但是 case class 有不超过 22 个字段的限制(online spark 是 1.6.3 with 2.10.4 的 scala).
正常class能做到吗?我必须实现哪些功能或接口?
还有一个“org.apache.spark.sql.functions.struct”,但是好像不能设置struct的字段名。 先谢谢了。

这个结构不需要定义大小写class,你可以这样创建结构类型:

val struct =
  StructType(
    StructField("a", IntegerType, true) ::
    StructField("b", LongType, false) ::
    StructField("c", BooleanType, false) :: Nil)

这个结构可以有任意长度。

那么你可以这样读取数据框

val df = sparkSession.read.schema(struct).//your read method

but seems that it can't set the name of the fields of the struct.

可以。例如:

import org.apache.spark.sql.functions._

spark.range(1).withColumn("foo", 
   struct($"id".alias("x"), lit("foo").alias("y"), struct($"id".alias("bar")))
).printSchema

root
 |-- id: long (nullable = false)
 |-- foo: struct (nullable = false)
 |    |-- x: long (nullable = false)
 |    |-- y: string (nullable = false)
 |    |-- col3: struct (nullable = false)
 |    |    |-- bar: long (nullable = false)