maropu commented on a change in pull request #30018:
URL: https://github.com/apache/spark/pull/30018#discussion_r509021645
##########
File path:
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
##########
@@ -475,6 +476,58 @@ object RemoveRedundantAliases extends Rule[LogicalPlan] {
def apply(plan: LogicalPlan): LogicalPlan = removeRedundantAliases(plan,
AttributeSet.empty)
}
+/**
+ * Remove 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.
+ */
+object RemoveRedundantAggregates extends Rule[LogicalPlan] with AliasHelper {
+ def apply(plan: LogicalPlan): LogicalPlan = plan transformUp {
+ case upper @ Aggregate(_, _, lower: Aggregate) if lowerIsRedundant(upper,
lower) =>
+ val aliasMap = getAliasMap(lower)
+ upper.copy(
+ child = lower.child,
+ groupingExpressions = upper.groupingExpressions.map(replaceAlias(_,
aliasMap)),
+ aggregateExpressions = upper.aggregateExpressions.map(
+ replaceAliasButKeepOuter(_, aliasMap))
+ )
+ }
+
+ private def lowerIsRedundant(upper: Aggregate, lower: Aggregate): Boolean = {
+ val isDeterministic = upper.aggregateExpressions.forall(_.deterministic) &&
+ lower.aggregateExpressions.forall(_.deterministic)
Review comment:
> As a dummy example - one that counts the number of times it has been
called and returns that count. Even if it is not referenced, evaluating it
changes future results.
For example, I think `ColumnPruning` removes exprs not referenced by a upper
node even in the case above, so we can ignore it.
```
// v3.0.1
scala> sql("select a, b from (select a, b, rand() from t group by a, b)
group by a, b").explain(true)
== Analyzed Logical Plan ==
a: bigint, b: bigint
Aggregate [a#0L, b#1L], [a#0L, b#1L]
+- SubqueryAlias __auto_generated_subquery_name
+- Aggregate [a#0L, b#1L], [a#0L, b#1L, rand(-8085205063662585668) AS
rand(-8085205063662585668)#31]
+- SubqueryAlias spark_catalog.default.t
+- Relation[a#0L,b#1L] parquet
== Optimized Logical Plan ==
Aggregate [a#0L, b#1L], [a#0L, b#1L]
+- Aggregate [a#0L, b#1L], [a#0L, b#1L]
+- Relation[a#0L,b#1L] parquet
```
```
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]