Spark SQL:来自csv的自动模式

时间:2014-11-17 09:39:15

标签: scala csv 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")

有关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)

所以剩下的唯一问题就是如何做这个步骤   对于给定数量的属性动态map(p => Row(p(0), p(1).trim))

感谢您的支持! 约尔格

2 个答案:

答案 0 :(得分: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)

可能这个链接会对你有帮助。

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

答案 1 :(得分:5)

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