Spark Dataframes-按键归约

Spark Dataframes- Reducing By Key

假设我有这样的数据结构,其中 ts 是某个时间戳

case class Record(ts: Long, id: Int, value: Int)

考虑到大量这些记录,我想以每个 ID 的时间戳最高的记录结束。使用 RDD api 我认为以下代码可以完成工作:

def findLatest(records: RDD[Record])(implicit spark: SparkSession) = {
  records.keyBy(_.id).reduceByKey{
    (x, y) => if(x.ts > y.ts) x else y
  }.values
}

同样,这是我对数据集的尝试:

def findLatest(records: Dataset[Record])(implicit spark: SparkSession) = {
  records.groupByKey(_.id).mapGroups{
    case(id, records) => {
      records.reduceLeft((x,y) => if (x.ts > y.ts) x else y)
    }
  }
}

我一直在尝试找出如何使用数据帧实现类似的功能,但无济于事-我意识到我可以使用以下方法进行分组:

records.groupBy($"id")

但这给了我一个 RelationGroupedDataSet 并且我不清楚我需要编写什么聚合函数来实现我想要的 - 我见过的所有示例聚合似乎都专注于返回一个被聚合的列而不是整行。

是否可以使用数据帧实现此目的?

您可以使用 argmax 逻辑(参见 databricks example

例如,假设您的数据框名为 df,它包含 id、val、ts 列,您可以这样做:

import org.apache.spark.sql.functions._
val newDF = df.groupBy('id).agg.max(struct('ts, 'val)) as 'tmp).select($"id", $"tmp.*")

对于数据集,我这样做了,在 Spark 2.1.1 上测试

final case class AggregateResultModel(id: String,
                                      mtype: String,
                                      healthScore: Int,
                                      mortality: Float,
                                      reimbursement: Float)
.....
.....

// assume that the rawScores are loaded behorehand from json,csv files

val groupedResultSet = rawScores.as[AggregateResultModel].groupByKey( item => (item.id,item.mtype ))
      .reduceGroups( (x,y) => getMinHealthScore(x,y)).map(_._2)


// the binary function used in the reduceGroups

def getMinHealthScore(x : AggregateResultModel, y : AggregateResultModel): AggregateResultModel = {
    // complex logic for deciding between which row to keep
    if (x.healthScore > y.healthScore) { return y }
    else if (x.healthScore < y.healthScore) { return x }
    else {

      if (x.mortality < y.mortality) { return y }
      else if (x.mortality > y.mortality) { return x }
      else  {

        if(x.reimbursement < y.reimbursement)
          return x
        else
          return y

      }

    }

  }