gpt4 book ai didi

scala - Spark SQL : automatic schema from csv

转载 作者:行者123 更新时间:2023-12-02 05:09:22 25 4
gpt4 key购买 nike

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)) 动态地获取给定数量的属性?

感谢您的支持!约尔格

最佳答案

您可以使用spark-csv您可以在其中节省一些击键次数,而无需定义列名称并自动使用标题。

关于scala - Spark SQL : automatic schema from csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26969620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com