apache-spark - spark处理csv文件中的json数据
问题描述
如何处理 csv 文件中的 json 数据我正在尝试使用 from_json 但是我需要指定我的模式,因为我的模式会不断变化。
样本输入:-
userid type data
26594 p.v {}
26594 s.s {"sIds":["1173","1342","12345"]}
26594 s.r {"bp":"sw"}
26594 p.v {}
26594 s.r {"c":"tracking","action":"n","label":"ank"}
26593 p.v {}
26594 p.sr {"pId":"11234","pName":"sahkas","s":"n","is":"F","totalCount":0,"scount":0}
我希望将其转换为数据框,我们可以使用它来查询 json。
寻找像这样的输出: -
userid type data_sids data_bp data_c data_action data_label
26594 p.v null null null null null
26594 s.s 1173 null null null null
26594 s.s 1173 null null null null
26594 s.s 1342 null null null null
26594 s.s 12345 null null null null
26594 s.r null sw null null null
这是可行的吗?
你能帮我解决这个问题吗?
谢谢,
安库什·雷迪。
解决方案
My advice is working with RDDs for this task. Write something like this:
rdd = # collection of Rows with the following fields: userid, type, data - your CSV
def flatten_json(userid, type, data_json):
final_row = {"userid": userid, "type": type, "data_sids": data_json["sids"], ...}
return Row(**final_row)
rdd = rdd.map(lambda row: flatten_json(row["userid"], row["type"], row["data"]))
df = spark.createDataFrame(rdd)
And that is it :)
推荐阅读
- kubernetes - Kubernetes 的 Grafana 仪表板,为每个 pod 及其资源限制提供单独的简单视图
- ios - 没有收到来自 Firebase 控制台的推送通知
- c# - 如何在列表框中设置文本块的背景颜色?
- postgresql - 不能从 db.QueryRow() 推断出错误
- python - 如何提取列名的两个特定字符并将它们附加到另一个列名?
- node.js - 无法在 Google Cloud Function 中加载 node_modules(index.js,不在项目根目录上)
- java - Java中的循环不可变链表
- javascript - 使用ajax将数据从php发送到图表
- javascript - 如何从 Google Analytics 跟踪器获取电子商务交易 ID
- linux - 排除 vcd2fst 分段错误时调试信息不正确