使用Apache Spark和Java对DataFrame进行分组和聚合?

时间:2016-01-25 15:35:18

标签: java apache-spark apache-spark-sql

我在Spark中加载了以下架构的DataFrame:

电子邮件, 名字, 姓, ORDER_ID

如何通过电子邮件对其进行分组,计算每个组中的记录并使用此模式返回DataFrane:

电子邮件, 名字, 姓, ORDER_COUNT

1 个答案:

答案 0 :(得分:3)

这是在 Scala

中执行此操作的方法
val df = sc.parallelize(Seq(("a","b","c",1),("a","b","c",2),("x","xb","xc",3),("y","yb","yc",4),("x","xb","xc",5))).toDF("email","first_name","last_name","order_id")

df.registerTempTable("df")

sqlContext.sql("select * from (select email, count(*) as order_count from df group by email ) d1 join df d2 on d1.email = d2.email")

Java 中,考虑到您已经创建了DataFrame,它实际上是相同的代码:

 
DataFrame results = sqlContext.sql("select * from (select email, count(*) as order_count from df group by email ) d1 join df d2 on d1.email = d2.email");

尽管如此,甚至认为这是一种直接的解决方案,但我认为这是一种不好的做法,因为您的代码难以维护和发展。更清洁的解决方案是:

DataFrame email_count = df.groupBy("email").count();
DataFrame results2 = email_count.join(df, email_count.col("email").equalTo(df.col("email"))).drop(df.col("email"));