【问题标题】:How to combine where and groupBy in Spark's DataFrame?如何在 Spark DataFrame 中结合 where 和 group By?
【发布时间】:2017-07-02 23:42:13
【问题描述】:

如何在 Apache Spark 1.6 的 where 子句中使用聚合函数?

考虑以下DataFrame

+---+------+
| id|letter|
+---+------+
|  1|     a|
|  2|     b|
|  3|     b|
+---+------+

如何选择letter 多次出现的所有行,即预期输出为

+---+------+
| id|letter|
+---+------+
|  2|     b|
|  3|     b|
+---+------+

这显然不起作用:

df.where(
  df.groupBy($"letter").count()>1
)

我的示例是关于 count,但我也希望能够使用其他聚合函数(其结果)。

编辑:

只是为了计数,我只是想出了以下解决方案:

df.groupBy($"letter").agg(
  collect_list($"id").as("ids")
 )
.where(size($"ids") > 1)
.withColumn("id", explode($"ids"))
.drop($"ids")

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    你可以使用左半连接:

    df.join(
      broadcast(df.groupBy($"letter").count.where($"count" > 1)),
      Seq("letter"),
      "leftsemi"
    )
    

    或窗口函数:

    import org.apache.spark.sql.expressions.Window
    
    df
      .withColumn("count", count($"*").over(Window.partitionBy("letter")))
      .where($"count" > 1)
    

    在 Spark 2.0 或更高版本中,您可以使用布隆过滤器,但在 1.x 中不可用

    【讨论】:

      猜你喜欢
      • 2016-11-15
      • 2012-07-17
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多