org.apache.spark.sql.types.DataTypeException:不支持的dataType:IntegerType

时间:2016-03-30 14:27:44

标签: scala apache-spark apache-spark-sql

我是Spark和Scala的新手我遇到了这个异常,我正在尝试添加一些额外的字段,即StructField到使用Spark SQL从数据框检索到的现有StructType,以及gettting以下异常。

代码段:

val dfStruct:StructType=parquetDf.select("columnname").schema
dfStruct.add("newField","IntegerType",true)

线程“main”中的异常

 org.apache.spark.sql.types.DataTypeException: Unsupported dataType: IntegerType. If you have a struct and a field name of it has any special characters, please use backticks (`) to quote that field name, e.g. `x+y`. Please note that backtick itself is not supported in a field name.
    at org.apache.spark.sql.types.DataTypeParser$class.toDataType(DataTypeParser.scala:95)
    at org.apache.spark.sql.types.DataTypeParser$$anon$1.toDataType(DataTypeParser.scala:107)
    at org.apache.spark.sql.types.DataTypeParser$.parse(DataTypeParser.scala:111)

我可以看到jira上有一些与此异常相关的未解决的问题,但无法理解。我使用Spark 1.5.1版本

https://mail-archives.apache.org/mod_mbox/spark-issues/201508.mbox/%3CJIRA.12852533.1438855066000.143133.1440397426473@Atlassian.JIRA%3E

https://mail-archives.apache.org/mod_mbox/spark-issues/201508.mbox/%3CJIRA.12852533.1438855066000.143133.1440397426473@Atlassian.JIRA%3E

https://issues.apache.org/jira/browse/SPARK-9685

1 个答案:

答案 0 :(得分:1)

当您使用StructType.add以下签名时:

add(name: String, dataType: String, nullable: Boolean)

dataType字符串应与.simpleString.typeName对应。对于IntegerType,它是int

import org.apache.spark.sql.types._

IntegerType.simpleString
// String = int

integer

IntegerType.typeName
// String = integer

所以你需要的是这样的:

val schema = StructType(Nil)

schema.add("foo", "int", true)
// org.apache.spark.sql.types.StructType = 
//   StructType(StructField(foo,IntegerType,true))

schema.add("foo", "integer", true)
// org.apache.spark.sql.types.StructType = 
//   StructType(StructField(foo,IntegerType,true))

如果您想传递IntegerType,则必须DataType而不是String

schema.add("foo", IntegerType, true)