在Spark Scala中创建ArrayType列



要创建的模式的结构:

|-- col1: boolean (nullable = true)
|-- col2: array (nullable = true)
|    |-- element: struct (containsNull = true)
|    |    |-- col2_1: boolean (nullable = true)
|    |    |-- col2_2: string (nullable = true)

创建模式的代码:

val prodSchema = StructType(Array(StructField("col1", StringType), StructField("col2",ArrayType(Array(StructField("element",StructType(Array(StructField("col2_1",StringType)))))))))

错误:

found   : Array[org.apache.spark.sql.types.StructField]
required: org.apache.spark.sql.types.DataType
StructField("col2",ArrayType(Array(StructField("element",StructType(Array(StructField("col2_1",StringType)))))))

有关如何纠正此模式错误的任何建议。

我想你可以这样写:

val prodSchema =
  StructType(
    List(
      StructField("col1", BooleanType),
      StructField("col2", ArrayType(
        StructType(
          List(
            StructField("col2_1", BooleanType),
            StructField("col2_2",StringType)
          )
        )
      ))
    )
  )

prodSchema.printTreeString()
root
 |-- col1: boolean (nullable = true)
 |-- col2: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- col2_1: boolean (nullable = true)
 |    |    |-- col2_2: string (nullable = true)

尝试以下:

val schema = StructType(Seq(  
    StructField("col1",BooleanType,false),
    StructField("col2",ArrayType(StructType(Seq(  
                       StructField("col2_1",BooleanType,true),
                       StructField("col2_2",StringType,true)
                         )))
               )))

您可以使用架构DSL创建架构:

val col2 = new StructType().add($"col2_1".boolean).add($"col2_2".string)
val schema = new StructType()
                 .add($"col1".boolean)
                 .add($"col2".array(col2))
schema.printTreeString()
root
 |-- col1: boolean (nullable = true)
 |-- col2: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- col2_1: boolean (nullable = true)
 |    |    |-- col2_2: string (nullable = true)

希望它有帮助。

相关内容

  • 没有找到相关文章

最新更新