输入数据的格式如下:
+--------------------+-------------+--------------------+
| date | user | product |
+--------------------+-------------+--------------------+
| 2016-10-01 | Tom | computer |
+--------------------+-------------+--------------------+
| 2016-10-01 | Tom | iphone |
+--------------------+-------------+--------------------+
| 2016-10-01 | Jhon | book |
+--------------------+-------------+--------------------+
| 2016-10-02 | Tom | pen |
+--------------------+-------------+--------------------+
| 2016-10-02 | Jhon | milk |
+--------------------+-------------+--------------------+
,输出格式如下:
+-----------+-----------------------+
| user | products |
+-----------------------------------+
| Tom | computer,iphone,pen |
+-----------------------------------+
| Jhon | book,milk |
+-----------------------------------+
输出显示每个用户按订单日期购买的所有产品。
我想用Spark处理这些数据,你能帮我吗?谢谢你。
最好使用map-reduceBykey()组合而不是groupBy..假设数据中没有
#Read the data using val ordersRDD = sc.textFile("/file/path")
val ordersRDD = sc.parallelize( List(("2016-10-01","Tom","computer"),
("2016-10-01","Tom","iphone"),
("2016-10-01","Jhon","book"),
("2016-10-02","Tom","pen"),
("2016-10-02","Jhon","milk")))
#group by (date, user), sort by key & reduce by user & concatenate products
val dtusrGrpRDD = ordersRDD.map(rec => ((rec._2, rec._1), rec._3))
.sortByKey().map(x=>(x._1._1, x._2))
.reduceByKey((acc, v) => acc+","+v)
#if needed, make it to DF
scala> dtusrGrpRDD.toDF("user", "product").show()
+----+-------------------+
|user| product|
+----+-------------------+
| Tom|computer,iphone,pen|
|Jhon| book,milk|
+----+-------------------+
如果您正在使用HiveContext(您应该使用):
使用python的例子:from pyspark.sql.functions import collect_set
df = ... load your df ...
new_df = df.groupBy("user").agg(collect_set("product").alias("products"))
如果你不想在产品中删除结果列表,你可以使用collect_list。
对于数据帧,它是两行:
import org.apache.spark.sql.functions.collect_list
//collect_set nistead of collect_list if you don't want duplicates
val output = join.groupBy("user").agg(collect_list($"product"))
GroupBy将给你一个分组的用户集post,你可以在分组的数据集上迭代和collect_list或collect_set。