Spark SQL:来自csv的自动模式

js8*_*s84 7 csv scala apache-spark apache-spark-sql

spark sql是否提供了自动加载csv数据的方法?我找到了以下Jira:https://issues.apache.org/jira/browse/SPARK-2360但它已关闭....

目前我将加载一个csv文件,如下所示:

case class Record(id: String, val1: String, val2: String, ....)

 sc.textFile("Data.csv")
.map(_.split(",")) 
.map { r =>                  
   Record(r(0),r(1), .....)
}.registerAsTable("table1")
Run Code Online (Sandbox Code Playgroud)

有关csv文件自动模式扣除的任何提示吗?特别是a)我如何生成一个代表模式的类,以及b)如何自动填充它(即Record(r(0),r(1),.....))?

更新:我在这里找到了对模式生成的部分答案:http: //spark.apache.org/docs/1.1.0/sql-programming-guide.html#data-sources

// The schema is encoded in a string
val schemaString = "name age"
// Generate the schema based on the string of schema
val schema =
 StructType(
schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, true)))
// Convert records of the RDD (people) to Rows.
val rowRDD = people.map(_.split(",")).map(p => Row(p(0), p(1).trim))
// Apply the schema to the RDD.
val peopleSchemaRDD = sqlContext.applySchema(rowRDD, schema)
Run Code Online (Sandbox Code Playgroud)

那么剩下的唯一问题是如何map(p => Row(p(0), p(1).trim))针对给定数量的属性动态地执行该步骤 ?

感谢您的支持!约尔格

Dev*_*M S 5

val schemaString = "name age".split(" ")
// Generate the schema based on the string of schema
val schema =   StructType(schemaString.map(fieldName => StructField(fieldName, StringType, true)))
val lines = people.flatMap(x=> x.split("\n"))
val rowRDD = lines.map(line=>{
  Row.fromSeq(line.split(" "))
})
val peopleSchemaRDD = sqlContext.applySchema(rowRDD, schema)
Run Code Online (Sandbox Code Playgroud)

可能是这个链接会帮助你.

http://devslogics.blogspot.in/2014/11/spark-sql-automatic-schema-from-csv.html


dim*_*sli 5

您可以使用spark-csv,您可以保存一些键击,而无需定义列名称并自动使用标题.