首页 > 解决方案 > 从具有键值对的列中获取部分值并将其分配给 Spark Dataframe 中的新列

问题描述

我有一个如下的数据框

+----+-----------------------------+
|id  | att                         |
+----+-----------------------------+
| 25 | {"State":"abc","City":"xyz"}|
| 26 | null                        |
| 27 | {"State":"pqr"}             |
+----+-----------------------------+

如果 att 列具有 city 属性,我想要一个具有列 id 和 city 的数据框,否则为 null

+----+------+
|id  | City | 
+----+------+
| 25 | xyz  |
| 26 | null |
| 27 | null |
+----+------+

语言:斯卡拉

标签: scalaapache-sparkapache-spark-sql

解决方案


您可以使用from_json解析您的 json 数据并将其转换为 Map。然后使用以下方法之一访问地图项:

import org.apache.spark.sql.functions.from_json
import org.apache.spark.sql.types.{MapType, StringType}

import sparkSession.implicits._
val df = Seq(
  (25, """{"State":"abc","City":"xyz"}"""),
  (26, null),
  (27, """{"State":"pqr"}""")
).toDF("id", "att")

val schema = MapType(StringType, StringType)

df.select($"id", from_json($"att", schema).getItem("City").as("City"))

//or df.select($"id", from_json($"att", schema)("City").as("City"))
//or df.select($"id", element_at(from_json($"att", schema), "City").as("City"))

// +---+----+
// | id|City|
// +---+----+
// | 25| xyz|
// | 26|null|
// | 27|null|
// +---+----+

推荐阅读