2017-09-06 62 views
1

我有一個JSON字符串,如下面一個數據幀從數據框中創建地圖火花斯卡拉

aaa | bbb | ccc |ddd | eee   
-------------------------------------- 
    100 | xxxx | 123 |yyy|2017 
    100 | yyyy | 345 |zzz|2017 
    200 | rrrr | 500 |qqq|2017 
    300 | uuuu | 200 |ttt|2017 
    200 | iiii | 500 |ooo|2017 

我想要得到的結果作爲

{100,[{xxxx:{123,yyy}},{yyyy:{345,zzz}}],2017} 
{200,[{rrrr:{500,qqq}},{iiii:{500,ooo}}],2017} 
{300,[{uuuu:{200,ttt}}],2017} 

請幫助

+0

你的標題和問題根本不匹配。 – philantrovert

+0

我應該提及什麼 – gayathri

+0

您建議的輸出不是json。 – Rumoku

回答

1

這工作:

val df = data 
    .withColumn("cd", array('ccc, 'ddd)) // create arrays of c and d 
    .withColumn("valuesMap", map('bbb, 'cd)) // create mapping 
    .withColumn("values", collect_list('valuesMap) // collect mappings 
       .over(Window.partitionBy('aaa))) 
    .withColumn("eee", first('eee) // e is constant, just get first value of Window 
       .over(Window.partitionBy('aaa))) 
    .select("aaa", "values", "eee") // select only columns that are in the question selected 
    .select(to_json(struct("aaa", "values", "eee")).as("value")) // create JSON 

Ma確保你有進口org.apache.spark.sql.functions._org.apache.spark.sql.expression._

+0

謝謝Gaweda。但是partitionby不起作用。但現在的要求是變化。我有如下列表 – gayathri

+0

@gayathri你是什麼意思的「不工作」?我已經在您的數據上進行了測試。如果你想使用普通的String列表,你可以使用IntelliJ(scala 2.10.6).withColumn(「valuesMap」,map('bbb,'cd))來實現collect() –

+0

Hi Gaweda, aso over(Window.partitionBy('aaa))無法識別。我已經導入了sql.functions請幫助 – gayathri