apache-spark - 在 Spark 中推断 json 数据方案的一种方法
问题描述
假设我有带有 column 的数据框data
。在本专栏中,我有一个内部带有 json 的字符串。诀窍是 json 并不总是完整的,某些行中可能缺少某些属性。
请参阅下面的示例以了解清楚
column_name_placeholder | data
foo {"attr1":1}
foo {"attr2":2}
bar {"attr0":"str"}
bar {"attr3":"po"}
我正在寻找的是一种为“column_name_placeholder”中的每个键推断完整 json 模式的方法
所以答案是这样的
foo
{
"attr1":int,
"attr2":int
}
bar
{
"attr0":string,
"attr3":string
}
我成像的唯一方法是下降到 RDD 级别并在 map 阶段使用某种 3rd 方库推断模式,然后在 reduce 阶段再次将该模式与一些 3rd 方库合并
我错过了一些火花*魔法吗?
解决方案
您可以转换为 RDD 并使用再次读取spark.read.json
并让它推断架构。
示例column_name_placeholder = bar
:
spark.read.json(
df.filter("column_name_placeholder = 'bar'").rdd.map(lambda row: row.data)
).printSchema()
#root
# |-- attr0: string (nullable = true)
# |-- attr3: string (nullable = true)
推荐阅读
- sql - Rails Active Records 同时使用最大值和最小值
- mysql - MySQL 远程连接(复制)
- ldap - OpenLDAP - 将 open-ldap 定义的属性添加到自定义类
- angular-material - angular5材料无法在表格中显示任何数据
- c++ - 为什么我不能使用 std::unique_ptr 作为“模板
类”的论点? - python - Python 日志记录 - 仅适用于自己导入的模块
- arrays - AngularJS 嵌套 ng-repeat 连接来自两个 JSON 数组的 ID
- ios - iOS swift:在旋转动画中间更改imageview图像
- android - 访问 Fragment 中的资产
- sql - 如何在年和年-1 的列中编写查询让值?