将Scala数据框列合并为单个案例类

时间:2019-02-28 20:21:15

标签: scala apache-spark apache-spark-dataset

我有一个看起来像这样的数据框:

+--------+-----+--------------------+
|     uid|  iid|               color|
+--------+-----+--------------------+
|41344966| 1305|                 red| 
|41344966| 1305|               green|

我想尽可能有效地做到这一点:

+--------+--------------------+
|     uid|     recommendations|
+--------+--------------------+
|41344966|      [[2174, red...|
|41345063|    [[2174, green...|
|41346177|   [[2996, orange...|
|41349171|   [[2174, purple...|

res98: org.apache.spark.sql.Dataset[userRecs] = [uid: int, recommendations: array<struct<iid:int,color:string>>]

所以我想按uid将记录分组为对象数组。每个对象都是具有参数iid和color的类。

case class itemData (iid: Int, color: String)

case class userRecs (uid: Int, recommendations: Array[itemData])

1 个答案:

答案 0 :(得分:2)

这是您想要的吗?

scala> case class itemData (iid: Int, color: String)
defined class itemData

scala> case class userRecs (uid: Int, recommendations: Array[itemData])
defined class userRecs

scala> val df = spark.createDataset(Seq(
    (41344966,1305,"red"),
    (41344966,1305,"green"),
    (41344966,2174,"red"),
    (41345063,2174,"green"),
    (41346177,2996,"orange"),
    (41349171,2174,"purple")
)).toDF("uid", "iid", "color")
df: org.apache.spark.sql.DataFrame = [uid: int, iid: int ... 1 more field]

scala> (df.select($"uid", struct($"iid",$"color").as("itemData"))
        .groupBy("uid")
        .agg(collect_list("itemData").as("recommendations"))
        .as[userRecs]
        .show())
+--------+--------------------+
|     uid|     recommendations|
+--------+--------------------+
|41344966|[[1305, red], [13...|
|41345063|     [[2174, green]]|
|41346177|    [[2996, orange]]|
|41349171|    [[2174, purple]]|
+--------+--------------------+