Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ package org.apache.spark.sql.catalyst.optimizer
import org.apache.spark.sql.catalyst.analysis.PullOutNondeterministic
import org.apache.spark.sql.catalyst.expressions.{AliasHelper, AttributeSet}
import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LogicalPlan}
import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LogicalPlan, Project}
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.catalyst.trees.TreePattern.AGGREGATE

Expand All @@ -47,6 +47,10 @@ object RemoveRedundantAggregates extends Rule[LogicalPlan] with AliasHelper {
} else {
newAggregate
}

case agg @ Aggregate(groupingExps, _, child) if agg.groupOnly && child.deterministic &&
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does child.deterministic matter here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We had a test like this before:

test("Remove redundant aggregate with non-deterministic upper") {
val query = relation
.groupBy('a)('a)
.groupBy('a)('a, rand(0) as 'c)
.analyze
val expected = relation
.groupBy('a)('a, rand(0) as 'c)
.analyze
val optimized = Optimize.execute(query)
comparePlans(optimized, expected)
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

which means child.deterministic doesn't matter? The test you posted did optimize out one aggregate.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry. This test:

test("Keep non-redundant aggregate - upper references non-deterministic non-grouping") {
val query = relation
.groupBy('a)('a, ('a + rand(0)) as 'c)
.groupBy('a, 'c)('a, 'c)
.analyze
val optimized = Optimize.execute(query)
comparePlans(optimized, query)
}

child.distinctKeys.exists(_.subsetOf(AttributeSet(groupingExps))) =>
Project(agg.aggregateExpressions, child)
}

private def isLowerRedundant(upper: Aggregate, lower: Aggregate): Boolean = {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.spark.sql.catalyst.plans.logical

import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeSet, ExpressionSet, NamedExpression}
import org.apache.spark.sql.catalyst.plans.LeftExistence

/**
* A visitor pattern for traversing a [[LogicalPlan]] tree and propagate the distinct attributes.
*/
object DistinctKeyVisitor extends LogicalPlanVisitor[Set[AttributeSet]] {

private def projectDistinctKeys(
keys: Set[ExpressionSet], projectList: Seq[NamedExpression]): Set[AttributeSet] = {
val expressions = keys.flatMap(_.toSet)
projectList.filter {
case a: Alias => expressions.exists(_.semanticEquals(a.child))
case ne => expressions.exists(_.semanticEquals(ne))
}.toSet.subsets(keys.map(_.size).min).filter { s =>
val references = s.map {
case a: Alias => a.child
case ne => ne
}
keys.exists(_.equals(ExpressionSet(references)))
}.map(s => AttributeSet(s.map(_.toAttribute))).toSet
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about

    val outputSet = ExpressionSet(projectList.map(_.toAttribute))
    val aliases = projectList.filter(_.isInstanceOf[Alias])
    if (aliases.isEmpty) return keys.filter(_.subsetOf(outputSet))

    val aliasedDistinctKeys = keys.map { expressionSet =>
      expressionSet.map { expression =>
        expression transform {
          case expr: Expression =>
            aliases
              .collectFirst { case a: Alias if a.child.semanticEquals(expr) => a.toAttribute }
              .getOrElse(expr)
        }
      }
    }
    aliasedDistinctKeys.collect {
      case es: ExpressionSet if es.subsetOf(outputSet) => ExpressionSet(es)
    }

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If one expression has multiple aliases, we need to further expand the distinct keys set. We can do it later as it's rather a corner case.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK

}

override def default(p: LogicalPlan): Set[AttributeSet] = Set.empty[AttributeSet]

override def visitAggregate(p: Aggregate): Set[AttributeSet] = {
val groupingExps = ExpressionSet(p.groupingExpressions) // handle group by a, a
projectDistinctKeys(Set(groupingExps), p.aggregateExpressions)
}

override def visitDistinct(p: Distinct): Set[AttributeSet] = {
Set(p.outputSet)
}

override def visitExcept(p: Except): Set[AttributeSet] =
if (!p.isAll && p.deterministic) Set(p.outputSet) else default(p)

override def visitExpand(p: Expand): Set[AttributeSet ] = default(p)

override def visitFilter(p: Filter): Set[AttributeSet ] = p.child.distinctKeys

override def visitGenerate(p: Generate): Set[AttributeSet ] = default(p)

override def visitGlobalLimit(p: GlobalLimit): Set[AttributeSet ] = p.child.distinctKeys
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if the limit value is 1 or 0, all output columns are distinct.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1


override def visitIntersect(p: Intersect): Set[AttributeSet ] = {
if (!p.isAll && p.deterministic) Set(p.outputSet) else default(p)
}

override def visitJoin(p: Join): Set[AttributeSet] = {
p.joinType match {
case LeftExistence(_) => p.left.distinctKeys
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shall we exclude ExistenceJoin?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK

case _ => default(p)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for left outer, we can propagate from right side.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

spark.sql("create table t1(a int, b int) using parquet")
spark.sql("create table t2(x int, y int) using parquet")

spark.sql("insert into t1 values(1, 1), (2, 2)")
spark.sql("insert into t2 values(3, 3), (4, 4)")

spark.sql("select * from t1 left join (select distinct * from t2)t2 on t1.a = t2.x and t1.b = t2.y").show

The output is:

+---+---+----+----+
|  a|  b|   x|   y|
+---+---+----+----+
|  2|  2|null|null|
|  1|  1|null|null|
+---+---+----+----+

We can't distinguish the distinct keys.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry my fault. We can propagate the left side distinct keys if p.right.distinctKeys.exists(_.subsetOf(rightJoinKeySet))

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

}
}

override def visitLocalLimit(p: LocalLimit): Set[AttributeSet] = p.child.distinctKeys

override def visitPivot(p: Pivot): Set[AttributeSet] = default(p)

override def visitProject(p: Project): Set[AttributeSet] = {
if (p.child.distinctKeys.nonEmpty) {
projectDistinctKeys(p.child.distinctKeys.map(ExpressionSet(_)), p.projectList)
} else {
default(p)
}
}

override def visitRepartition(p: Repartition): Set[AttributeSet] = p.child.distinctKeys

override def visitRepartitionByExpr(p: RepartitionByExpression): Set[AttributeSet] =
p.child.distinctKeys

override def visitSample(p: Sample): Set[AttributeSet] = default(p)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For Sample without replacement, we can propagate the distinct keys from child.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1


override def visitScriptTransform(p: ScriptTransformation): Set[AttributeSet] = default(p)

override def visitUnion(p: Union): Set[AttributeSet] = default(p)

override def visitWindow(p: Window): Set[AttributeSet] = p.child.distinctKeys

override def visitTail(p: Tail): Set[AttributeSet] = p.child.distinctKeys

override def visitSort(p: Sort): Set[AttributeSet] = p.child.distinctKeys

override def visitRebalancePartitions(p: RebalancePartitions): Set[AttributeSet] =
p.child.distinctKeys

override def visitWithCTE(p: WithCTE): Set[AttributeSet] = default(p)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CTE can also propagate distinct keys from child.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ abstract class LogicalPlan
extends QueryPlan[LogicalPlan]
with AnalysisHelper
with LogicalPlanStats
with LogicalPlanDistinctKeys
with QueryPlanConstraints
with Logging {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.spark.sql.catalyst.plans.logical

import org.apache.spark.sql.catalyst.expressions.AttributeSet

/**
* A trait to add distinct attributes to [[LogicalPlan]]. For example:
* {{{
* SELECT a, b, SUM(c) FROM Tab1 GROUP BY a, b
* // returns a, b
* }}}
*/
trait LogicalPlanDistinctKeys { self: LogicalPlan =>
lazy val distinctKeys: Set[AttributeSet] = DistinctKeyVisitor.visit(self)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we add a config for this feature? If the config is off, here we just return Set.empty

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

e.g. spark.sql.optimizer.propagateDistinctKeys.enabled

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK

}
Loading