【问题标题】:How to do custom operations on GroupedData in Spark?如何在 Spark 中对 GroupedData 进行自定义操作?
【发布时间】:2016-05-17 10:51:29
【问题描述】:

我想重写一些用 RDD 编写的代码以使用 DataFrame。在我发现这个之前,它工作得非常顺利:

 events
  .keyBy(row => (row.getServiceId + row.getClientCreateTimestamp + row.getClientId, row) )
  .reduceByKey((e1, e2) => if(e1.getClientSendTimestamp <= e2.getClientSendTimestamp) e1 else e2)
  .values

上手很简单

 events
  .groupBy(events("service_id"), events("client_create_timestamp"), events("client_id"))

但是接下来呢?如果我想遍历当前组中的每个元素怎么办?甚至可能吗? 提前致谢。

【问题讨论】:

    标签: scala apache-spark grouping


    【解决方案1】:

    GroupedData不能直接使用。数据没有物理分组,它只是一个逻辑操作。您必须应用agg 方法的一些变体,例如:

    events
     .groupBy($"service_id", $"client_create_timestamp", $"client_id")
     .min("client_send_timestamp")
    

    events
     .groupBy($"service_id", $"client_create_timestamp", $"client_id")
     .agg(min($"client_send_timestamp"))
    

    其中client_send_timestamp 是您要聚合的列。

    如果您想保留信息而不是仅聚合 join 或使用窗口函数 - 请参阅 Find maximum row per group in Spark DataFrame

    Spark 还支持用户定义的聚合函数 - 请参阅 How to define and use a User-Defined Aggregate Function in Spark SQL?

    Spark 2.0+

    您可以使用 Dataset.groupByKey 将组公开为迭代器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 2018-05-13
      相关资源
      最近更新 更多