【问题标题】:How to create schema (StructType) with one or more StructTypes?如何使用一个或多个 StructTypes 创建模式(StructType)?
【发布时间】:2019-01-08 16:53:40
【问题描述】:

我正在尝试在另一个StructType 中创建一个StructType,但它只允许添加一个StructField。我找不到任何添加StructType 的方法。

如何为以下字符串表示创建StructType 架构?

struct<abc:struct<name:string>,pqr:struct<address:string>>

【问题讨论】:

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


    【解决方案1】:

    Spark SQL 有一个隐藏的特性,可以使用所谓的 Schema DSL(即没有很多圆括号等)来定义模式。

    import org.apache.spark.sql.types._
    val name = new StructType().add($"name".string)
    scala> println(name.simpleString)
    struct<name:string>
    
    val address = new StructType().add($"address".string)
    scala> println(address.simpleString)
    struct<address:string>
    
    val schema = new StructType().add("abc", name).add("pqr", address)
    scala> println(schema.simpleString)
    struct<abc:struct<name:string>,pqr:struct<address:string>>
    
    scala> schema.simpleString == "struct<abc:struct<name:string>,pqr:struct<address:string>>"
    res4: Boolean = true
    
    scala> schema.printTreeString
    root
     |-- abc: struct (nullable = true)
     |    |-- name: string (nullable = true)
     |-- pqr: struct (nullable = true)
     |    |-- address: string (nullable = true)
    

    【讨论】:

      【解决方案2】:

      structField 是类型和名称的组合,因此您可以这样做:

      StructType(Seq(StructField("structName", StructType(Seq(StructField("name", StringType), StructField("address", StringType))))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-26
        • 1970-01-01
        • 1970-01-01
        • 2021-12-12
        • 1970-01-01
        • 1970-01-01
        • 2020-01-04
        • 1970-01-01
        相关资源
        最近更新 更多