Spark dropDuplicates 源代码

Waq*_*med 1 open-source apache-spark apache-spark-sql

我正在查看 Spark 源代码以了解dropDuplicates方法的工作原理。在方法定义中有一个方法Deduplicate调用。但我找不到它的定义或参考。如果有人能指出我正确的方向,那就太好了。链接在这里在此处输入图片说明

Gri*_*aub 5

它在火花催化剂中,请参见此处

由于实现有点混乱,我将添加一些解释。

目前的实现Deduplicate是:

/** A logical plan for `dropDuplicates`. */
case class Deduplicate(
    keys: Seq[Attribute],
    child: LogicalPlan) extends UnaryNode {

  override def output: Seq[Attribute] = child.output
}
Run Code Online (Sandbox Code Playgroud)

不清楚这里发生了什么,但如果你看一下Optimizer类,你会看到ReplaceDeduplicateWithAggregate对象,然后它变得更加清晰。

/**
 * Replaces logical [[Deduplicate]] operator with an [[Aggregate]] operator.
 */
object ReplaceDeduplicateWithAggregate extends Rule[LogicalPlan] {
  def apply(plan: LogicalPlan): LogicalPlan = plan transform {
    case Deduplicate(keys, child) if !child.isStreaming =>
      val keyExprIds = keys.map(_.exprId)
      val aggCols = child.output.map { attr =>
        if (keyExprIds.contains(attr.exprId)) {
          attr
        } else {
          Alias(new First(attr).toAggregateExpression(), attr.name)(attr.exprId)
        }
      }
      // SPARK-22951: Physical aggregate operators distinguishes global aggregation and grouping
      // aggregations by checking the number of grouping keys. The key difference here is that a
      // global aggregation always returns at least one row even if there are no input rows. Here
      // we append a literal when the grouping key list is empty so that the result aggregate
      // operator is properly treated as a grouping aggregation.
      val nonemptyKeys = if (keys.isEmpty) Literal(1) :: Nil else keys
      Aggregate(nonemptyKeys, aggCols, child)
  }
}
Run Code Online (Sandbox Code Playgroud)

底线,用于dfcol1, col2, col3, col4

df.dropDuplicates("col1", "col2") 
Run Code Online (Sandbox Code Playgroud)

或多或少

df.groupBy("col1", "col2").agg(first("col3"), first("col4"))
Run Code Online (Sandbox Code Playgroud)