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

How to wrap spark streaming output in array brackets?

Spark:2.3.0 Scala: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"}

您需要重新定义架构,因为您希望将输入视为 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"}]|
//+----------------+