Spark dropDuplicates源代码

时间:2018-06-20 12:26:36

标签: apache-spark apache-spark-sql open-source

我正在研究Spark源代码,以了解dropDuplicates方法的工作方式。在方法定义中,有一个方法Deduplicate调用。但是我找不到它的定义或参考。如果有人能指出我正确的方向,那就太好了。链接为hereenter image description here

1 个答案:

答案 0 :(得分:3)

它是火花催化剂,请参见here

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

Deduplicate的当前实现是:

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

  override def output: Seq[Attribute] = child.output
}

目前尚不清楚这里会发生什么,但是如果您看一下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)
  }
}

底线,对于df,列为col1, col2, col3, col4

df.dropDuplicates("col1", "col2") 

或多或少

df.groupBy("col1", "col2").agg(first("col3"), first("col4"))