Spark:选择任意类型的值的特定索引



所以我有一个DataFrame,其中一列的类型是WrappedArray(JSON(。在每一个中,JSON都有一个格式[String,String]我已经成功地访问了数组的内部,现在我有了一个Any类型的列,其中每个值都有一个[String,String]。重点是:我只想取这两个字符串的第一个值,但如果我尝试类似列(0(的东西,它会引发一个错误,因为Any没有索引。如何访问此值?

我现在的代码是:

val schema = StructType(Seq(
StructField("productId", StringType, true),
StructField("name", StringType, true)
))
df.withColumn("column", from_json($"column"(0), schema) )

我的df:的模式

root
|-- customerId: string (nullable = true)
|-- column: struct (nullable = true)
|    |-- productId: string (nullable = true)
|    |-- name: string (nullable = true)
|-- date: date (nullable = true)

我自己设法解决了这个问题。答案很明显:我没有创建一个包含两个值的struct类型的列,而是创建了一个具有相同值的MapType。

我的最终代码:

df.withColumn("column", from_json($"column"(0), MapType(StringType, StringType)) )

然后,为了访问新列的键和值:

.select("column.productId", "column.name")

最新更新