2017-10-31 4 views
5

私はこの他の列を派生させるために、列をjsonオブジェクトとして一時的に格納する方法はありますか?

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

のようなキーと値のペアを持つデータセットを持って、私はそのように、私はそれを文字列にキャストすることなく、このJSON形式のデータ構造を保つことができる方法はありJSON

{"likes": ["dogs","sports"], "hates": ["birds"], "eats": ["cheese"]} 

にそれを回します列ごとに列を増やすことができますか?私は、このようなものを見たいと思います。すべての列が追加された文字列から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"))); 

答えて

3

あなたは

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]| 
+---+--------+-------+--------------+ 
関連する問題