我想动态生成包含报表标题记录的数据框,因此请根据以下字符串的值创建数据框:
scope.itemFilter = {members: ['john','nick']
但是现在我想对数据做同样的事情(实际上是相同的数据,即元数据)。
我创建了一个RDD:
val headerDescs : String = "Name,Age,Location"
val headerSchema = StructType(headerDescs.split(",").map(fieldName => StructField(fieldName, StringType, true)))
然后我打算使用createDataFrame来创建它:
val headerRDD = sc.parallelize(headerDescs.split(","))
然而失败是因为val headerDf = sqlContext.createDataFrame(headerRDD, headerSchema)
期待createDataframe
,但是我的RDD是一个字符串数组 - 我找不到将RDD转换为行RDD然后映射的方法动态的字段。我已经看过的示例假设您事先知道了列数,但我希望能够最终能够在不更改代码的情况下更改列 - 例如,在文件中包含列。
基于第一个答案的代码摘录:
RDD[Row]
执行此结果:
val headerDescs : String = "Name,Age,Location"
// create the schema from a string, splitting by delimiter
val headerSchema = StructType(headerDescs.split(",").map(fieldName => StructField(fieldName, StringType, true)))
// create a row from a string, splitting by delimiter
val headerRDDRows = sc.parallelize(headerDescs.split(",")).map( a => Row(a))
val headerDf = sqlContext.createDataFrame(headerRDDRows, headerSchema)
headerDf.show()
答案 0 :(得分:3)
要将RDD[Array[String]]
转换为RDD[Row]
,您需要执行以下步骤:
import org.apache.spark.sql.Row
val headerRDD = sc.parallelize(Seq(headerDescs.split(","))).map(x=>Row(x(0),x(1),x(2)))
scala> val headerSchema = StructType(headerDescs.split(",").map(fieldName => StructField(fieldName, StringType, true)))
headerSchema: org.apache.spark.sql.types.StructType = StructType(StructField(Name,StringType,true), StructField(Age,StringType,true), StructField(Location,StringType,true))
scala> val headerRDD = sc.parallelize(Seq(headerDescs.split(","))).map(x=>Row(x(0),x(1),x(2)))
headerRDD: org.apache.spark.rdd.RDD[org.apache.spark.sql.Row] = MapPartitionsRDD[6] at map at <console>:34
scala> val headerDf = sqlContext.createDataFrame(headerRDD, headerSchema)
headerDf: org.apache.spark.sql.DataFrame = [Name: string, Age: string, Location: string]
scala> headerDf.printSchema
root
|-- Name: string (nullable = true)
|-- Age: string (nullable = true)
|-- Location: string (nullable = true)
scala> headerDf.show
+----+---+--------+
|Name|Age|Location|
+----+---+--------+
|Name|Age|Location|
+----+---+--------+
这会给你一个RDD[Row]
阅读文件
val vRDD = sc.textFile("..**filepath**.").map(_.split(",")).map(a => Row.fromSeq(a))
val headerDf = sqlContext.createDataFrame(vRDD , headerSchema)
使用Spark-CSV包:
val df = sqlContext.read
.format("com.databricks.spark.csv")
.option("header", "true") // Use first line of all files as header
.schema(headerSchema) // defining based on the custom schema
.load("cars.csv")
或强>
val df = sqlContext.read
.format("com.databricks.spark.csv")
.option("header", "true") // Use first line of all files as header
.option("inferSchema", "true") // Automatically infer data types
.load("cars.csv")
您可以在documentation中找到各种选项。