以下代码失败:
val RDD = sparkContext.parallelize(Seq(
Row("123", new java.lang.Integer(456))
))
val schema = StructType(
StructField("str", StringType) ::
StructField("dbl", DoubleType) :: Nil
)
val df = sqlContext.createDataFrame(RDD, schema)
df.collect().foreach(println)
除了这个异常(exception):
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
at scala.runtime.BoxesRunTime.unboxToDouble(BoxesRunTime.java:119)
at org.apache.spark.sql.catalyst.expressions.BaseGenericInternalRow$class.getDouble(rows.scala:44)
at org.apache.spark.sql.catalyst.expressions.GenericInternalRow.getDouble(rows.scala:221)
....
请注意,这只是一个测试用例,在实际情况下,类型 java.lang.Integer 是从另一个函数返回的,因此我无法从头开始使用未装箱的数值创建 Row。
如何解决这个问题?
最佳答案
Integer 不是 Double,Spark 的提示是正确的。手动类型转换:
val toDouble = udf {x: Int => x.toDouble}
df.withColumn("dbl", toDouble(df.col("ints")))
关于scala - SparkSQL.createDataFrame 中出现奇怪的类型转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35594759/