gpt4 book ai didi

apache-spark - 我如何将一列临时存储为 json 对象以派生其他列?

转载 作者:行者123 更新时间:2023-12-04 04:00:35 25 4
gpt4 key购买 nike

我有一个像这样的键值对的数据集

likes=dogs;hates=birds;likes=sports;eats=cheese

然后我把它变成json
{"likes": ["dogs","sports"], "hates": ["birds"], "eats": ["cheese"]}

有没有一种方法可以保留这个 json 数据结构而不将其转换为字符串,这样我就可以逐行从中派生出更多列?我希望它看起来像这样,而不必从每列添加的字符串中解码 json。
        Dataset<Row> df1 = df.withColumn("interests", callUDF("to_json", col("interests")))
.withColumn("likes", callUDF("extract_from_json", "likes", col("interests")))
.withColumn("hates", callUDF("extract_from_json", "hates", col("interests")))
.withColumn("hates", callUDF("extract_from_json", "eats", col("interests")));

最佳答案

如果您正在处理原始文件

likes=dogs;hates=birds;likes=sports;eats=cheese

然后你可以用 sc.textFile 读取它,然后做一些简单的 RDD 操作。
val df = sc.textFile(file)
.flatMap(x => x.split(";"))
.map(x => (x.split("=")(0), x.split("=")(1)))
.toDF("interest","value")

df.withColumn("tmp",lit(1)).groupBy("tmp").pivot("interest").agg(collect_list("value"))

+---+--------+-------+--------------+
|tmp| eats| hates| likes|
+---+--------+-------+--------------+
| 1|[cheese]|[birds]|[dogs, sports]|
+---+--------+-------+--------------+

关于apache-spark - 我如何将一列临时存储为 json 对象以派生其他列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47029504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com