代码之家  ›  专栏  ›  技术社区  ›  jmoney

如何将火花流输出包装在数组括号中?

  •  1
  • jmoney  · 技术社区  · 8 年前

    火花: 2.3.0 斯卡拉: 2.11.12

    我正在使用Spark结构流从Kafka主题流,并将结果输出到另一个Kafka主题。

    val mySchema = StructType(StructField("foo", StringType, true) :: Nil)
    

    输入数据 [{"foo":"bar"}]

    当我使用 select(from_json(col(A), mySchema)) 方法从数组内部解析对象并将其放入我的架构中。

    我要做的是,在过滤数据帧转换的最后,包装 mySchema 在数组中,使输出看起来相同: [“foo”:“bar”]

    但是,我只能得到结果 Dataframe 不带数组括号的输出: {"foo":"bar"}

    1 回复  |  直到 7 年前
        1
  •  1
  •   philantrovert    8 年前

    您需要重新定义您的模式,因为您希望将输入视为 struct 类型,即 array<struct<foo:string>>

    val mySchema = ArrayType(StructType(Seq(StructField("foo", StringType, true))),true)
    val target = df.select(from_json(col("A"), mySchema).alias("A"))
    
    target.printSchema
    //root
    // |-- A: array (nullable = true)
    // |    |-- element: struct (containsNull = true)
    // |    |    |-- foo: string (nullable = true)
    
    target.select(to_json($"A")).show
    //+----------------+
    //|structstojson(A)|
    //+----------------+
    //| [{"foo":"bar"}]|
    //+----------------+
    
    推荐文章