You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2022/03/29 14:31:52 UTC

[GitHub] [spark] wangyum opened a new pull request #36005: [SPARK-38506][SQL] Push partial aggregation through join

wangyum opened a new pull request #36005:
URL: https://github.com/apache/spark/pull/36005


   ### What changes were proposed in this pull request?
   
   This PR add a new rule to push down the partial aggregation through join if it cannot be planned as broadcast hash join. For example:
   ```
   set spark.sql.autoBroadcastJoinThreshold=-1;
   CREATE TABLE t1 using parquet AS SELECT id AS a, id AS b, id AS c FROM range(10);
   CREATE TABLE t2 using parquet AS SELECT id AS x, id AS y FROM range(8);
   SELECT c, y FROM t1 JOIN t2 ON t1.a = t2.x GROUP BY c, y;
   ```
   
   Before this pr:
   ```
   == Optimized Logical Plan ==
   Aggregate [c#19L, y#21L], [c#19L, y#21L], false
   +- Project [c#19L, y#21L]
      +- Join Inner, (a#17L = x#20L)
         :- Project [a#17L, c#19L]
         :  +- Filter isnotnull(a#17L)
         :     +- Relation default.t1[a#17L,b#18L,c#19L] parquet
         +- Filter isnotnull(x#20L)
            +- Relation default.t2[x#20L,y#21L] parquet
   ```
   
   After this pr:
   ```
   == Optimized Logical Plan ==
   Aggregate [c#19L, y#21L], [c#19L, y#21L], false
   +- Project [c#19L, y#21L]
      +- Join Inner, (a#17L = x#20L)
         :- Aggregate [c#19L, a#17L], [c#19L, a#17L], true
         :  +- Project [a#17L, c#19L]
         :     +- Filter isnotnull(a#17L)
         :        +- Relation default.t1[a#17L,b#18L,c#19L] parquet
         +- Aggregate [y#21L, x#20L], [y#21L, x#20L], true
            +- Filter isnotnull(x#20L)
               +- Relation default.t2[x#20L,y#21L] parquet
   ```
   
   ### Why are the changes needed?
   
   1. Reduce shuffle data to improve query performance.
   2. Many databases have similar rules:
       Teradata: https://docs.teradata.com/r/Teradata-VantageTM-SQL-Request-and-Transaction-Processing/March-2019/Join-Planning-and-Optimization/Partial-GROUP-BY-Block-Optimization
       Calcite: https://issues.apache.org/jira/browse/CALCITE-366
       Hive: https://issues.apache.org/jira/browse/HIVE-10785
       Trino: https://github.com/trinodb/trino/blob/375/core/trino-main/src/main/java/io/trino/sql/planner/iterative/rule/PushPartialAggregationThroughJoin.java
       Presto: https://github.com/prestodb/presto/blob/0.271/presto-main/src/main/java/com/facebook/presto/sql/planner/iterative/rule/PushPartialAggregationThroughJoin.java
   
   
   ### Does this PR introduce _any_ user-facing change?
   
   No.
   
   ### How was this patch tested?
   
   Unit test and TPC-DS benchmark test.
   
   SQL | Before this PR(Seconds) | After this PR(Seconds)
   -- | -- | --
   q37 | 31 | 14
   q38 | 60 | 28
   q54 | 10 | 12
   q82 | 52 | 25
   q87 | 46 | 41
   
   
   


-- 
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.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] wangyum commented on pull request #36005: [SPARK-38506][SQL] Push partial aggregation through join

Posted by GitBox <gi...@apache.org>.
wangyum commented on pull request #36005:
URL: https://github.com/apache/spark/pull/36005#issuecomment-1082596952


   q54 is slower than before because it can't reduce lots of data, but we can improve it by https://issues.apache.org/jira/browse/SPARK-38505
   
   Before | After
   -- | --
   ![image](https://user-images.githubusercontent.com/5399861/160748009-7d1913a8-3c46-4690-ab3c-d38dc4a59eaf.png) | ![image](https://user-images.githubusercontent.com/5399861/160748691-99e46476-3958-4eaf-b84b-8ae39577b8e0.png)
   
   


-- 
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.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] wangyum commented on a change in pull request #36005: [SPARK-38506][SQL] Push partial aggregation through join

Posted by GitBox <gi...@apache.org>.
wangyum commented on a change in pull request #36005:
URL: https://github.com/apache/spark/pull/36005#discussion_r837614622



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala
##########
@@ -964,6 +965,7 @@ case class Range(
 case class Aggregate(
     groupingExpressions: Seq[Expression],
     aggregateExpressions: Seq[NamedExpression],
+    isPartialOnly: Boolean,

Review comment:
       Adding a new LogicalPlan is not easy to maintain because lots of rules need to consider that rule. For example:
   
   https://github.com/apache/spark/blob/eb30a27e53158e64fffaa6d32ff9369ffbae0384/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala#L3814-L3816




-- 
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.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] wangyum commented on pull request #36005: [SPARK-38506][SQL] Push partial aggregation through join

Posted by GitBox <gi...@apache.org>.
wangyum commented on pull request #36005:
URL: https://github.com/apache/spark/pull/36005#issuecomment-1082599624


   cc @cloud-fan @sigmod 


-- 
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.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] wangyum commented on pull request #36005: [SPARK-38506][SQL] Push partial aggregation through join

Posted by GitBox <gi...@apache.org>.
wangyum commented on pull request #36005:
URL: https://github.com/apache/spark/pull/36005#issuecomment-1082007598


    TPC-DS q82 before | TPC-DS q82 after
   -- | --
    ![image](https://user-images.githubusercontent.com/5399861/160645477-af04eada-4e84-463b-a246-77e3b62ee134.png) | ![image](https://user-images.githubusercontent.com/5399861/160643343-cb790126-33b1-4aec-aa38-136cd7d8ee2a.png)
   


-- 
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.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] singhpk234 commented on a change in pull request #36005: [SPARK-38506][SQL] Push partial aggregation through join

Posted by GitBox <gi...@apache.org>.
singhpk234 commented on a change in pull request #36005:
URL: https://github.com/apache/spark/pull/36005#discussion_r838096257



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushPartialAggregationThroughJoin.scala
##########
@@ -0,0 +1,102 @@
+/*
+ * 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.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys
+import org.apache.spark.sql.catalyst.plans.Inner
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern._
+
+/**
+ * Push down the partial aggregation through join if it cannot be planned as broadcast hash join.
+ */
+object PushPartialAggregationThroughJoin extends Rule[LogicalPlan]
+  with PredicateHelper
+  with JoinSelectionHelper {
+
+  private def isSupportPushdown(aggregateExpressions: Seq[NamedExpression]): Boolean = {
+    aggregateExpressions.forall {
+      case _: Attribute => true
+      case Alias(_: Attribute, _) => true
+      case Alias(_: Literal, _) => true
+      case _ => false
+    }
+  }
+
+  private def split(expressions: Seq[NamedExpression], left: LogicalPlan, right: LogicalPlan) = {
+    val (leftExpressions, rest) =
+      expressions.partition(e => e.references.nonEmpty && e.references.subsetOf(left.outputSet))
+    val (rightExpressions, remainingExpressions) =
+      rest.partition(e => e.references.nonEmpty && e.references.subsetOf(right.outputSet))
+
+    (leftExpressions, rightExpressions, remainingExpressions)
+  }
+
+  private def pushdown(
+      agg: Aggregate,
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      join: Join): LogicalPlan = {
+    val (leftGroupExps, rightGroupExps, remainingGroupExps) =
+      split(agg.groupingExpressions.map(_.asInstanceOf[NamedExpression]), join.left, join.right)
+
+    val (leftAggExps, rightAggExps, remainingAggExps) =
+      split(agg.aggregateExpressions, join.left, join.right)
+
+    val newLeftGroup = leftGroupExps ++ leftKeys.flatMap(_.references)
+    val newLeftAgg: Seq[NamedExpression] = newLeftGroup ++ leftAggExps.flatMap(_.references)
+
+    val newRightGroup = rightGroupExps ++ rightKeys.flatMap(_.references)
+    val newRightAgg: Seq[NamedExpression] = newRightGroup ++ rightAggExps.flatMap(_.references)
+
+    val newJoin = join.copy(
+      left = Aggregate(newLeftGroup.distinct, newLeftAgg.distinct, true, join.left),
+      right = Aggregate(newRightGroup.distinct, newRightAgg.distinct, true, join.right))
+
+    if (agg.isPartialOnly) {
+      Project(agg.aggregateExpressions, newJoin)
+    } else {
+      agg.copy(child = newJoin)
+    }
+  }
+
+  def apply(plan: LogicalPlan): LogicalPlan = plan.transformWithPruning(
+    _.containsAllPatterns(AGGREGATE, JOIN), ruleId) {
+    case agg @ Aggregate(_, _, _, join: Join)
+        if join.left.isInstanceOf[Aggregate] || join.right.isInstanceOf[Aggregate] =>
+      agg
+    case agg @ Aggregate(_, _, _, Project(_, join: Join))
+        if join.left.isInstanceOf[Aggregate] || join.right.isInstanceOf[Aggregate] =>
+      agg
+
+    case agg @ Aggregate(_, aggExprs, _,
+          join @ ExtractEquiJoinKeys(Inner, leftKeys, rightKeys, None, _, left, right, _))
+        if isSupportPushdown(aggExprs) && (leftKeys ++ rightKeys).nonEmpty &&
+          !canPlanAsBroadcastHashJoin(join, conf) =>
+      pushdown(agg, leftKeys, rightKeys, join)
+
+    case agg @ Aggregate(_, aggExprs, _, Project(projectList,
+          join @ ExtractEquiJoinKeys(Inner, leftKeys, rightKeys, None, _, left, right, _)))

Review comment:
       [question] can we extend this to LeftSemi / LeftAnti as well, as we can very well have a parent agg on non-join key, then in this case we could push partialAgg of aggExpr, left join-key down in the left side of join to reduce our join input. 
   As per my understanding it might  be possible, Am I am missing something here ? 

##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
##########
@@ -88,6 +88,7 @@ abstract class Optimizer(catalogManager: CatalogManager)
         LimitPushDownThroughWindow,
         ColumnPruning,
         GenerateOptimization,
+        PushPartialAggregationThroughJoin,

Review comment:
       should we do this post Collpase project rule ?
   As we could miss this case : 
   
   Agg -> Proj -> Proj -> Join (inner / non-broadcastable)




-- 
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.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] wangyum commented on a change in pull request #36005: [SPARK-38506][SQL] Push partial aggregation through join

Posted by GitBox <gi...@apache.org>.
wangyum commented on a change in pull request #36005:
URL: https://github.com/apache/spark/pull/36005#discussion_r837614622



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala
##########
@@ -964,6 +965,7 @@ case class Range(
 case class Aggregate(
     groupingExpressions: Seq[Expression],
     aggregateExpressions: Seq[NamedExpression],
+    isPartialOnly: Boolean,

Review comment:
       Adding a new LogicalPlan is not easy to maintain because lots of rules need to consider that LogicalPlan. For example:
   
   https://github.com/apache/spark/blob/eb30a27e53158e64fffaa6d32ff9369ffbae0384/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala#L3814
   https://github.com/apache/spark/blob/c16a66a64bf9599b4fefcdc2beaad7c4f2a4517e/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RemoveRedundantAggregates.scala#L34
   https://github.com/apache/spark/blob/efe43306fcab18f076f755c81c0406ebc1a5fee9/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala#L1539
   




-- 
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.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] wangyum commented on a change in pull request #36005: [SPARK-38506][SQL] Push partial aggregation through join

Posted by GitBox <gi...@apache.org>.
wangyum commented on a change in pull request #36005:
URL: https://github.com/apache/spark/pull/36005#discussion_r838325046



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushPartialAggregationThroughJoin.scala
##########
@@ -0,0 +1,102 @@
+/*
+ * 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.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys
+import org.apache.spark.sql.catalyst.plans.Inner
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern._
+
+/**
+ * Push down the partial aggregation through join if it cannot be planned as broadcast hash join.
+ */
+object PushPartialAggregationThroughJoin extends Rule[LogicalPlan]
+  with PredicateHelper
+  with JoinSelectionHelper {
+
+  private def isSupportPushdown(aggregateExpressions: Seq[NamedExpression]): Boolean = {
+    aggregateExpressions.forall {
+      case _: Attribute => true
+      case Alias(_: Attribute, _) => true
+      case Alias(_: Literal, _) => true
+      case _ => false
+    }
+  }
+
+  private def split(expressions: Seq[NamedExpression], left: LogicalPlan, right: LogicalPlan) = {
+    val (leftExpressions, rest) =
+      expressions.partition(e => e.references.nonEmpty && e.references.subsetOf(left.outputSet))
+    val (rightExpressions, remainingExpressions) =
+      rest.partition(e => e.references.nonEmpty && e.references.subsetOf(right.outputSet))
+
+    (leftExpressions, rightExpressions, remainingExpressions)
+  }
+
+  private def pushdown(
+      agg: Aggregate,
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      join: Join): LogicalPlan = {
+    val (leftGroupExps, rightGroupExps, remainingGroupExps) =
+      split(agg.groupingExpressions.map(_.asInstanceOf[NamedExpression]), join.left, join.right)
+
+    val (leftAggExps, rightAggExps, remainingAggExps) =
+      split(agg.aggregateExpressions, join.left, join.right)
+
+    val newLeftGroup = leftGroupExps ++ leftKeys.flatMap(_.references)
+    val newLeftAgg: Seq[NamedExpression] = newLeftGroup ++ leftAggExps.flatMap(_.references)
+
+    val newRightGroup = rightGroupExps ++ rightKeys.flatMap(_.references)
+    val newRightAgg: Seq[NamedExpression] = newRightGroup ++ rightAggExps.flatMap(_.references)
+
+    val newJoin = join.copy(
+      left = Aggregate(newLeftGroup.distinct, newLeftAgg.distinct, true, join.left),
+      right = Aggregate(newRightGroup.distinct, newRightAgg.distinct, true, join.right))
+
+    if (agg.isPartialOnly) {
+      Project(agg.aggregateExpressions, newJoin)
+    } else {
+      agg.copy(child = newJoin)
+    }
+  }
+
+  def apply(plan: LogicalPlan): LogicalPlan = plan.transformWithPruning(
+    _.containsAllPatterns(AGGREGATE, JOIN), ruleId) {
+    case agg @ Aggregate(_, _, _, join: Join)
+        if join.left.isInstanceOf[Aggregate] || join.right.isInstanceOf[Aggregate] =>
+      agg
+    case agg @ Aggregate(_, _, _, Project(_, join: Join))
+        if join.left.isInstanceOf[Aggregate] || join.right.isInstanceOf[Aggregate] =>
+      agg
+
+    case agg @ Aggregate(_, aggExprs, _,
+          join @ ExtractEquiJoinKeys(Inner, leftKeys, rightKeys, None, _, left, right, _))
+        if isSupportPushdown(aggExprs) && (leftKeys ++ rightKeys).nonEmpty &&
+          !canPlanAsBroadcastHashJoin(join, conf) =>
+      pushdown(agg, leftKeys, rightKeys, join)
+
+    case agg @ Aggregate(_, aggExprs, _, Project(projectList,
+          join @ ExtractEquiJoinKeys(Inner, leftKeys, rightKeys, None, _, left, right, _)))

Review comment:
       We can support it step by step.




-- 
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.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] wangyum commented on a change in pull request #36005: [SPARK-38506][SQL] Push partial aggregation through join

Posted by GitBox <gi...@apache.org>.
wangyum commented on a change in pull request #36005:
URL: https://github.com/apache/spark/pull/36005#discussion_r838323032



##########
File path: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
##########
@@ -88,6 +88,7 @@ abstract class Optimizer(catalogManager: CatalogManager)
         LimitPushDownThroughWindow,
         ColumnPruning,
         GenerateOptimization,
+        PushPartialAggregationThroughJoin,

Review comment:
       It should work in the next iteration.




-- 
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.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org