我有一个像这样的键值对的数据集
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]|
+---+--------+-------+--------------+
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句