如何自动创建 StructType 以将 RDD 传递给 DataFrame

How to automate StructType creation for passing RDD to DataFrame

我想将 RDD 另存为 parquet 文件。为此,我将 RDD 传递给 DataFrame,然后使用一个结构将 DataFrame 保存为镶木地板文件:

    val aStruct = new StructType(Array(StructField("id",StringType,nullable = true),
                                       StructField("role",StringType,nullable = true)))
    val newDF = sqlContext.createDataFrame(filtered, aStruct)

问题是假设所有列都是StringType,如何为所有列自动创建aStruct?还有,nullable = true是什么意思?这是否意味着所有空值都将被替换为 Null

为什么不使用内置的 toDF

scala> val myRDD = sc.parallelize(Seq(("1", "roleA"), ("2", "roleB"), ("3", "roleC")))
myRDD: org.apache.spark.rdd.RDD[(String, String)] = ParallelCollectionRDD[60] at parallelize at <console>:27

scala> val colNames = List("id", "role")
colNames: List[String] = List(id, role)

scala> val myDF = myRDD.toDF(colNames: _*)
myDF: org.apache.spark.sql.DataFrame = [id: string, role: string]

scala> myDF.show
+---+-----+
| id| role|
+---+-----+
|  1|roleA|
|  2|roleB|
|  3|roleC|
+---+-----+

scala> myDF.printSchema
root
 |-- id: string (nullable = true)
 |-- role: string (nullable = true)

scala> myDF.write.save("myDF.parquet")

nullable=true 只是意味着指定的列可以包含 null 值(这对于通常没有 null 值的 int 列尤其有用-- Int 没有 NAnull).