【问题标题】:Spark scala.collection.immutable.$colon$colon is not a valid external type for schema of stringSpark scala.collection.immutable.$colon$colon 不是字符串模式的有效外部类型
【发布时间】:2021-09-01 13:46:03
【问题描述】:

此代码不起作用的可能原因是什么以及如何修复它?是的,f1、f2、f3、f4 字段没有使用,但在生产代码中 getList 有一个参数 xml_data,所以我将 xml_data 字段传递给方法并获取 List[AnyRef]

def getList: List[AnyRef] = {
  List("string",
   new Integer(20),
   Decimal(BigDecimal(10000), 10, 2),
   Timestamp.valueOf("2021-01-01 10:00:00"),
   List("1","2","3"),
   List(1,2,3),
   List(Decimal(BigDecimal(10000), 10, 2)),
   List(Timestamp.valueOf("2021-01-01 10:00:00")),
   null,
   List(null))
}

...

val schema = StructType(Seq(
  StructField("string", StringType),
  StructField("int", IntegerType),
  StructField("decimal", DecimalType(10, 2)),
  StructField("timestamp", TimestampType),
  StructField("array_string", ArrayType(StringType)),
  StructField("array_int", ArrayType(IntegerType)),
  StructField("array_decimal", ArrayType(DecimalType(10, 2))),
  StructField("array_timestamp", ArrayType(TimestampType)),
  StructField("array_int", ArrayType(IntegerType)),
  StructField("array_string", ArrayType(StringType))
))

val encoder = RowEncoder(schema)

import spark.implicits._

List((1, 2, 3, 4))
  .toDF("f1", "f2", "f3", "f4")
  .as[Rec]
  .map(rec => {
    Row(getList)
  })(encoder)
  .show()

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    Row 不采用 List 而是采用 varargs 参数。要将该列表扩展为可变参数,您必须使用这种奇怪的类型归属 _*。否则,整个列表将被解释为第一个(也是唯一的)参数。

    List((1, 2, 3, 4))
      .toDF("f1", "f2", "f3", "f4")
      .as[Rec]
      .map(rec => {
        Row(getList :_*)
      })(encoder)
      .show()
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2019-03-22
    • 2021-07-23
    • 2020-02-15
    • 2021-11-29
    • 2022-08-16
    • 2013-01-24
    相关资源
    最近更新 更多