Nar*_*ren 12 scala apache-spark apache-spark-sql spark-dataframe
我正在从文本文件中读取数据框架的模式.该文件看起来像
id,1,bigint
price,2,bigint
sqft,3,bigint
zip_id,4,int
name,5,string
Run Code Online (Sandbox Code Playgroud)
我将解析后的数据类型映射到Spark Sql数据类型.创建数据框的代码是 -
var schemaSt = new ListBuffer[(String,String)]()
// read schema from file
for (line <- Source.fromFile("meta.txt").getLines()) {
val word = line.split(",")
schemaSt += ((word(0),word(2)))
}
// map datatypes
val types = Map("int" -> IntegerType, "bigint" -> LongType)
.withDefault(_ => StringType)
val schemaChanged = schemaSt.map(x => (x._1,types(x._2))
// read data source
val lines = spark.sparkContext.textFile("data source path")
val fields = schemaChanged.map(x => StructField(x._1, x._2, nullable = true)).toList
val schema = StructType(fields)
val rowRDD = lines
.map(_.split("\t"))
.map(attributes => Row.fromSeq(attributes))
// Apply the schema to the RDD
val new_df = spark.createDataFrame(rowRDD, schema)
new_df.show(5)
new_df.printSchema()
Run Code Online (Sandbox Code Playgroud)
但上述内容仅适用于StringType.对于IntegerType和LongType,它抛出异常 -
java.lang.RuntimeException:java.lang.String不是int模式的有效外部类型
和
java.lang.RuntimeException:java.lang.String不是bigint模式的有效外部类型.
提前致谢!
我有同样的问题,其原因是Row.fromSeq()电话.
如果在数组上调用它String,则结果Row是String's 的行.哪个与架构(bigint或int)中第二列的类型不匹配.
为了获得有效的数据帧Row.fromSeq(values: Seq[Any]),values参数的元素必须是与您的模式对应的类型.
| 归档时间: |
|
| 查看次数: |
19921 次 |
| 最近记录: |