-
Notifications
You must be signed in to change notification settings - Fork 28.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[SPARK-33122][SQL] Remove redundant aggregates in the Optimzier
### What changes were proposed in this pull request? Added optimizer rule `RemoveRedundantAggregates`. It removes redundant aggregates from a query plan. A redundant aggregate is an aggregate whose only goal is to keep distinct values, while its parent aggregate would ignore duplicate values. The affected part of the query plan for TPCDS q87: Before: ``` == Physical Plan == *(26) HashAggregate(keys=[], functions=[count(1)]) +- Exchange SinglePartition, true, [id=#785] +- *(25) HashAggregate(keys=[], functions=[partial_count(1)]) +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[]) +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[]) +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[]) +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[]) +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[]) +- Exchange hashpartitioning(c_last_name#61, c_first_name#60, d_date#26, 5), true, [id=#724] +- *(24) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[]) +- SortMergeJoin [coalesce(c_last_name#61, ), isnull(c_last_name#61), coalesce(c_first_name#60, ), isnull(c_first_name#60), coalesce(d_date#26, 0), isnull(d_date#26)], [coalesce(c_last_name#221, ), isnull(c_last_name#221), coalesce(c_first_name#220, ), isnull(c_first_name#220), coalesce(d_date#186, 0), isnull(d_date#186)], LeftAnti :- ... ``` After: ``` == Physical Plan == *(26) HashAggregate(keys=[], functions=[count(1)]) +- Exchange SinglePartition, true, [id=#751] +- *(25) HashAggregate(keys=[], functions=[partial_count(1)]) +- *(25) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[]) +- Exchange hashpartitioning(c_last_name#61, c_first_name#60, d_date#26, 5), true, [id=#694] +- *(24) HashAggregate(keys=[c_last_name#61, c_first_name#60, d_date#26], functions=[]) +- SortMergeJoin [coalesce(c_last_name#61, ), isnull(c_last_name#61), coalesce(c_first_name#60, ), isnull(c_first_name#60), coalesce(d_date#26, 0), isnull(d_date#26)], [coalesce(c_last_name#221, ), isnull(c_last_name#221), coalesce(c_first_name#220, ), isnull(c_first_name#220), coalesce(d_date#186, 0), isnull(d_date#186)], LeftAnti :- ... ``` ### Why are the changes needed? Performance improvements - few TPCDS queries have these kinds of duplicate aggregates. ### Does this PR introduce _any_ user-facing change? No ### How was this patch tested? UT Benchmarks (sf=5): OpenJDK 64-Bit Server VM 1.8.0_265-b01 on Linux 5.8.13-arch1-1 Intel(R) Core(TM) i5-6500 CPU 3.20GHz | Query | Before | After | Speedup | | ------| ------- | ------| ------- | | q14a | 44s | 44s | 1x | | q14b | 41s | 41s | 1x | | q38 | 6.5s | 5.9s | 1.1x | | q87 | 7.2s | 6.8s | 1.1x | | q14a-v2.7 | 55s | 53s | 1x | Closes #30018 from tanelk/SPARK-33122. Lead-authored-by: tanel.kiis@gmail.com <tanel.kiis@gmail.com> Co-authored-by: Tanel Kiis <tanel.kiis@reach-u.com> Signed-off-by: Takeshi Yamamuro <yamamuro@apache.org>
- Loading branch information
Showing
6 changed files
with
284 additions
and
52 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
74 changes: 74 additions & 0 deletions
74
...alyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/PullOutNondeterministic.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
/* | ||
* 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.analysis | ||
|
||
import org.apache.spark.sql.catalyst.expressions._ | ||
import org.apache.spark.sql.catalyst.plans.logical._ | ||
import org.apache.spark.sql.catalyst.rules.Rule | ||
|
||
/** | ||
* Pulls out nondeterministic expressions from LogicalPlan which is not Project or Filter, | ||
* put them into an inner Project and finally project them away at the outer Project. | ||
*/ | ||
object PullOutNondeterministic extends Rule[LogicalPlan] { | ||
override def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperatorsUp applyLocally | ||
|
||
val applyLocally: PartialFunction[LogicalPlan, LogicalPlan] = { | ||
case p if !p.resolved => p // Skip unresolved nodes. | ||
case p: Project => p | ||
case f: Filter => f | ||
|
||
case a: Aggregate if a.groupingExpressions.exists(!_.deterministic) => | ||
val nondeterToAttr = getNondeterToAttr(a.groupingExpressions) | ||
val newChild = Project(a.child.output ++ nondeterToAttr.values, a.child) | ||
a.transformExpressions { case e => | ||
nondeterToAttr.get(e).map(_.toAttribute).getOrElse(e) | ||
}.copy(child = newChild) | ||
|
||
// Don't touch collect metrics. Top-level metrics are not supported (check analysis will fail) | ||
// and we want to retain them inside the aggregate functions. | ||
case m: CollectMetrics => m | ||
|
||
// todo: It's hard to write a general rule to pull out nondeterministic expressions | ||
// from LogicalPlan, currently we only do it for UnaryNode which has same output | ||
// schema with its child. | ||
case p: UnaryNode if p.output == p.child.output && p.expressions.exists(!_.deterministic) => | ||
val nondeterToAttr = getNondeterToAttr(p.expressions) | ||
val newPlan = p.transformExpressions { case e => | ||
nondeterToAttr.get(e).map(_.toAttribute).getOrElse(e) | ||
} | ||
val newChild = Project(p.child.output ++ nondeterToAttr.values, p.child) | ||
Project(p.output, newPlan.withNewChildren(newChild :: Nil)) | ||
} | ||
|
||
private def getNondeterToAttr(exprs: Seq[Expression]): Map[Expression, NamedExpression] = { | ||
exprs.filterNot(_.deterministic).flatMap { expr => | ||
val leafNondeterministic = expr.collect { | ||
case n: Nondeterministic => n | ||
case udf: UserDefinedExpression if !udf.deterministic => udf | ||
} | ||
leafNondeterministic.distinct.map { e => | ||
val ne = e match { | ||
case n: NamedExpression => n | ||
case _ => Alias(e, "_nondeterministic")() | ||
} | ||
e -> ne | ||
} | ||
}.toMap | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
163 changes: 163 additions & 0 deletions
163
...c/test/scala/org/apache/spark/sql/catalyst/optimizer/RemoveRedundantAggregatesSuite.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
/* | ||
* 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.optimizer | ||
|
||
import org.apache.spark.api.python.PythonEvalType | ||
import org.apache.spark.sql.catalyst.dsl.expressions._ | ||
import org.apache.spark.sql.catalyst.dsl.plans._ | ||
import org.apache.spark.sql.catalyst.expressions.{Expression, PythonUDF} | ||
import org.apache.spark.sql.catalyst.plans.PlanTest | ||
import org.apache.spark.sql.catalyst.plans.logical.{LocalRelation, LogicalPlan} | ||
import org.apache.spark.sql.catalyst.rules.RuleExecutor | ||
import org.apache.spark.sql.types.IntegerType | ||
|
||
class RemoveRedundantAggregatesSuite extends PlanTest { | ||
|
||
object Optimize extends RuleExecutor[LogicalPlan] { | ||
val batches = Batch("RemoveRedundantAggregates", FixedPoint(10), | ||
RemoveRedundantAggregates) :: Nil | ||
} | ||
|
||
private def aggregates(e: Expression): Seq[Expression] = { | ||
Seq( | ||
count(e), | ||
PythonUDF("pyUDF", null, IntegerType, Seq(e), | ||
PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF, udfDeterministic = true) | ||
) | ||
} | ||
|
||
test("Remove redundant aggregate") { | ||
val relation = LocalRelation('a.int, 'b.int) | ||
for (agg <- aggregates('b)) { | ||
val query = relation | ||
.groupBy('a)('a, agg) | ||
.groupBy('a)('a) | ||
.analyze | ||
val expected = relation | ||
.groupBy('a)('a) | ||
.analyze | ||
val optimized = Optimize.execute(query) | ||
comparePlans(optimized, expected) | ||
} | ||
} | ||
|
||
test("Remove 2 redundant aggregates") { | ||
val relation = LocalRelation('a.int, 'b.int) | ||
for (agg <- aggregates('b)) { | ||
val query = relation | ||
.groupBy('a)('a, agg) | ||
.groupBy('a)('a) | ||
.groupBy('a)('a) | ||
.analyze | ||
val expected = relation | ||
.groupBy('a)('a) | ||
.analyze | ||
val optimized = Optimize.execute(query) | ||
comparePlans(optimized, expected) | ||
} | ||
} | ||
|
||
test("Remove redundant aggregate with different grouping") { | ||
val relation = LocalRelation('a.int, 'b.int) | ||
val query = relation | ||
.groupBy('a, 'b)('a) | ||
.groupBy('a)('a) | ||
.analyze | ||
val expected = relation | ||
.groupBy('a)('a) | ||
.analyze | ||
val optimized = Optimize.execute(query) | ||
comparePlans(optimized, expected) | ||
} | ||
|
||
test("Remove redundant aggregate with aliases") { | ||
val relation = LocalRelation('a.int, 'b.int) | ||
for (agg <- aggregates('b)) { | ||
val query = relation | ||
.groupBy('a + 'b)(('a + 'b) as 'c, agg) | ||
.groupBy('c)('c) | ||
.analyze | ||
val expected = relation | ||
.groupBy('a + 'b)(('a + 'b) as 'c) | ||
.analyze | ||
val optimized = Optimize.execute(query) | ||
comparePlans(optimized, expected) | ||
} | ||
} | ||
|
||
test("Remove redundant aggregate with non-deterministic upper") { | ||
val relation = LocalRelation('a.int, 'b.int) | ||
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) | ||
} | ||
|
||
test("Remove redundant aggregate with non-deterministic lower") { | ||
val relation = LocalRelation('a.int, 'b.int) | ||
val query = relation | ||
.groupBy('a, 'c)('a, rand(0) as 'c) | ||
.groupBy('a, 'c)('a, 'c) | ||
.analyze | ||
val expected = relation | ||
.groupBy('a, 'c)('a, rand(0) as 'c) | ||
.analyze | ||
val optimized = Optimize.execute(query) | ||
comparePlans(optimized, expected) | ||
} | ||
|
||
test("Keep non-redundant aggregate - upper has agg expression") { | ||
val relation = LocalRelation('a.int, 'b.int) | ||
for (agg <- aggregates('b)) { | ||
val query = relation | ||
.groupBy('a, 'b)('a, 'b) | ||
// The count would change if we remove the first aggregate | ||
.groupBy('a)('a, agg) | ||
.analyze | ||
val optimized = Optimize.execute(query) | ||
comparePlans(optimized, query) | ||
} | ||
} | ||
|
||
test("Keep non-redundant aggregate - upper references agg expression") { | ||
val relation = LocalRelation('a.int, 'b.int) | ||
for (agg <- aggregates('b)) { | ||
val query = relation | ||
.groupBy('a)('a, agg as 'c) | ||
.groupBy('c)('c) | ||
.analyze | ||
val optimized = Optimize.execute(query) | ||
comparePlans(optimized, query) | ||
} | ||
} | ||
|
||
test("Keep non-redundant aggregate - upper references non-deterministic non-grouping") { | ||
val relation = LocalRelation('a.int, 'b.int) | ||
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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters