【问题标题】:Trouble with DecimalType converting an array of attribute name and DataType to an array of StructField in Spark使用 DecimalType 将属性名称和 DataType 数组转换为 Spark 中的 StructField 数组的问题
【发布时间】:2017-12-21 19:31:21
【问题描述】:

我想映射一个包含不同 DataTypes 的数组来自动创建 StructField。但是我对 DecimalType 有一些问题。例如,如果我测试

val myType1 = StringType
val testString =  myType1.asInstanceOf[DataType]

我没有问题。但是下面的行

val myType2 = DecimalType
val testDecimal =  myType2.asInstanceOf[DataType]

我得到了这个例外:

Exception in thread "main" java.lang.ClassCastException: org.apache.spark.sql.types.DecimalType$ cannot be cast to org.apache.spark.sql.types.DataType

我不明白,因为在文档中我认为 DecimalType 继承了 DataType:

https://spark.apache.org/docs/2.0.2/api/java/org/apache/spark/sql/types/DecimalType.html.

所以我正在寻找所有“spark.sql.type”的父对象。

我的目标是绘制类似的地图:

Array(("name",StringType),("size", LongType),("att3",DecimalType),("age",IntegerType))

到一个 StructField 数组。

有人知道吗?

【问题讨论】:

  • 你为什么要把他们扔回DataType
  • 因为它包含在行中,不像我的例子。所以我得到了调用 myrow(0).asInstance[String] 的属性的名称和调用 myrow(1).asInstance[DataType] 的属性的类型。我得到了错误

标签: scala apache-spark


【解决方案1】:

当您仅使用 DecimalType 时,您将获得对 DecimalType 对象的引用,而不是确切的对象。

val a = DecimalType
a: org.apache.spark.sql.types.DecimalType.type = org.apache.spark.sql.types.DecimalType$@156bb545

而不是,

val a = DecimalType(10,0)
a: org.apache.spark.sql.types.DecimalType = DecimalType(10,0)

替代方案是使用:

myType2(10,0).asInstanceOf[DataType]
org.apache.spark.sql.types.DataType = DecimalType(10,0)

//or if you want max precision and scala

myType2.Unlimited.asInstanceOf[DataType]
org.apache.spark.sql.types.DataType = DecimalType(38,18)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    相关资源
    最近更新 更多