【问题标题】:How to access nested schema column?如何访问嵌套模式列?
【发布时间】:2019-06-09 03:51:03
【问题描述】:

我有一个带有 JSON 的 Kafka 流媒体源,例如{"type":"abc","1":"23.2"}.

查询给出以下异常:

org.apache.spark.sql.catalyst.parser.ParseException:  extraneous
input '.1' expecting {<EOF>, .......}
 == SQL == 
person.1

访问"person.1"的正确语法是什么?

我什至将DoubleType 更改为StringType,但这也没有用。只需保留person.type 并在selectExpr 中删除person.1,示例就可以正常工作:

val personJsonDf = inputDf.selectExpr("CAST(value AS STRING)")
val struct = new StructType()
  .add("type", DataTypes.StringType)
  .add("1", DataTypes.DoubleType)
val personNestedDf = personJsonDf
  .select(from_json($"value", struct).as("person"))
val personFlattenedDf = personNestedDf
  .selectExpr("person.type", "person.1")
val consoleOutput = personNestedDf.writeStream
  .outputMode("update")
  .format("console")
  .start()

【问题讨论】:

    标签: apache-spark apache-spark-sql spark-structured-streaming


    【解决方案1】:

    有趣,因为 select($"person.1") 应该可以正常工作(但您使用了 selectExpr,这可能会混淆 Spark SQL)。

    StructField(1,DoubleType,true) 不起作用,因为类型实际上应该是 StringType

    让我们看看...

    $ cat input.json
    {"type":"abc","1":"23.2"}
    
    val input = spark.read.text("input.json")
    scala> input.show(false)
    +-------------------------+
    |value                    |
    +-------------------------+
    |{"type":"abc","1":"23.2"}|
    +-------------------------+
    
    import org.apache.spark.sql.types._
    val struct = new StructType()
      .add("type", DataTypes.StringType)
      .add("1", DataTypes.StringType)
    val q = input.select(from_json($"value", struct).as("person"))
    scala> q.show
    +-----------+
    |     person|
    +-----------+
    |[abc, 23.2]|
    +-----------+
    
    val q = input.select(from_json($"value", struct).as("person")).select($"person.1")
    scala> q.show
    +----+
    |   1|
    +----+
    |23.2|
    +----+
    

    【讨论】:

      【解决方案2】:

      我已经使用person.*解决了这个问题

      +-----+--------+
      |type | 1      |
      +-----+--------+
      |abc  |23.2    |
      +-----+--------+
      

      【讨论】:

        猜你喜欢
        • 2019-02-08
        • 2019-02-27
        • 2018-12-05
        • 1970-01-01
        • 1970-01-01
        • 2011-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多