-
Notifications
You must be signed in to change notification settings - Fork 29k
[SPARK-36290][SQL] Pull out join condition #33522
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
bbe2193
Push down join condition evaluation
wangyum 837ebbe
Merge remote-tracking branch 'upstream/master' into SPARK-36290
wangyum 02f498d
Fix test
wangyum c16d606
Fix test
wangyum fc9fa2d
PullOutJoinCondition
wangyum 431e873
Fix test error
wangyum 990a1b4
Move rule to SparkOptimizer
wangyum f098c03
Fix
wangyum 6e65595
Move to Finish Analysis to infer more filters.
wangyum 29507cc
fix
wangyum 07eda27
fix
wangyum 457b0bf
Merge remote-tracking branch 'upstream/master' into SPARK-36290
wangyum 58c6c60
Merge Upstream
wangyum 0e0c085
Add more tests
wangyum c63f784
Push down EqualNullSafe join condition
wangyum 62a5ac0
Address comments
wangyum b988b9e
Remove !canPlanAsBroadcastHashJoin(j, conf)
wangyum 7f6edf8
Merge remote-tracking branch 'upstream/master' into SPARK-36290
wangyum 4aebe0a
Fix test error
wangyum c6fca9a
Address comments
wangyum File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
85 changes: 85 additions & 0 deletions
85
...atalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PullOutJoinCondition.scala
This file contains hidden or 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,85 @@ | ||
| /* | ||
| * 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 scala.collection.mutable.ArrayBuffer | ||
|
|
||
| import org.apache.spark.sql.catalyst.expressions.{Alias, And, EqualTo, NamedExpression, PredicateHelper} | ||
| import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys | ||
| import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project} | ||
| import org.apache.spark.sql.catalyst.rules.Rule | ||
| import org.apache.spark.sql.catalyst.trees.TreePattern.JOIN | ||
|
|
||
| /** | ||
| * This rule ensures that [[Join]] keys doesn't contain complex expressions in the | ||
| * optimization phase. | ||
| * | ||
| * Complex expressions are pulled out to a [[Project]] node under [[Join]] and are | ||
| * referenced in join condition. | ||
| * | ||
| * {{{ | ||
| * SELECT * FROM t1 JOIN t2 ON t1.a + 10 = t2.x ==> | ||
| * Project [a#0, b#1, x#2, y#3] | ||
| * +- Join Inner, ((spark_catalog.default.t1.a + 10)#8 = x#2) | ||
| * :- Project [a#0, b#1, (a#0 + 10) AS (spark_catalog.default.t1.a + 10)#8] | ||
| * : +- Filter isnotnull((a#0 + 10)) | ||
| * : +- Relation default.t1[a#0,b#1] parquet | ||
| * +- Filter isnotnull(x#2) | ||
| * +- Relation default.t2[x#2,y#3] parquet | ||
| * }}} | ||
| */ | ||
| object PullOutJoinCondition extends Rule[LogicalPlan] with PredicateHelper { | ||
|
|
||
| def apply(plan: LogicalPlan): LogicalPlan = plan.transformUpWithPruning(_.containsPattern(JOIN)) { | ||
| case j @ ExtractEquiJoinKeys(_, leftKeys, rightKeys, otherPredicates, _, left, right, _) | ||
| if j.resolved => | ||
| val complexLeftJoinKeys = new ArrayBuffer[NamedExpression]() | ||
| val complexRightJoinKeys = new ArrayBuffer[NamedExpression]() | ||
|
|
||
| val newLeftJoinKeys = leftKeys.map { expr => | ||
| if (!expr.foldable && expr.children.nonEmpty) { | ||
| val ne = Alias(expr, expr.sql)() | ||
| complexLeftJoinKeys += ne | ||
| ne.toAttribute | ||
| } else { | ||
| expr | ||
| } | ||
| } | ||
|
|
||
| val newRightJoinKeys = rightKeys.map { expr => | ||
| if (!expr.foldable && expr.children.nonEmpty) { | ||
| val ne = Alias(expr, expr.sql)() | ||
| complexRightJoinKeys += ne | ||
| ne.toAttribute | ||
| } else { | ||
| expr | ||
| } | ||
| } | ||
|
|
||
| if (complexLeftJoinKeys.nonEmpty || complexRightJoinKeys.nonEmpty) { | ||
| val newLeft = Project(left.output ++ complexLeftJoinKeys, left) | ||
| val newRight = Project(right.output ++ complexRightJoinKeys, right) | ||
| val newCond = (newLeftJoinKeys.zip(newRightJoinKeys) | ||
| .map { case (l, r) => EqualTo(l, r) } ++ otherPredicates) | ||
| .reduceLeftOption(And) | ||
| Project(j.output, j.copy(left = newLeft, right = newRight, condition = newCond)) | ||
| } else { | ||
| j | ||
| } | ||
| } | ||
| } |
97 changes: 97 additions & 0 deletions
97
...st/src/test/scala/org/apache/spark/sql/catalyst/optimizer/PullOutJoinConditionSuite.scala
This file contains hidden or 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,97 @@ | ||
| /* | ||
| * 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.dsl.expressions._ | ||
| import org.apache.spark.sql.catalyst.dsl.plans._ | ||
| import org.apache.spark.sql.catalyst.expressions.{Alias, Coalesce, IsNull, Literal, Substring, Upper} | ||
| import org.apache.spark.sql.catalyst.plans._ | ||
| import org.apache.spark.sql.catalyst.plans.logical._ | ||
| import org.apache.spark.sql.catalyst.rules._ | ||
|
|
||
| class PullOutJoinConditionSuite extends PlanTest { | ||
|
|
||
| private object Optimize extends RuleExecutor[LogicalPlan] { | ||
| val batches = | ||
| Batch("Pull out join condition", Once, | ||
| PullOutJoinCondition, | ||
| CollapseProject) :: Nil | ||
| } | ||
|
|
||
| private val testRelation = LocalRelation('a.string, 'b.int, 'c.int) | ||
| private val testRelation1 = LocalRelation('d.string, 'e.int) | ||
| private val x = testRelation.subquery('x) | ||
| private val y = testRelation1.subquery('y) | ||
|
|
||
| test("Pull out join keys evaluation(String expressions)") { | ||
| Seq(Upper("y.d".attr), Substring("y.d".attr, 1, 5)).foreach { udf => | ||
| val originalQuery = x.join(y, condition = Option('a === udf)).select('a, 'e) | ||
| val correctAnswer = x.select('a, 'b, 'c) | ||
| .join(y.select('d, 'e, Alias(udf, udf.sql)()), | ||
| condition = Option('a === s"`${udf.sql}`".attr)).select('a, 'e) | ||
|
|
||
| comparePlans(Optimize.execute(originalQuery.analyze), correctAnswer.analyze) | ||
| } | ||
| } | ||
|
|
||
| test("Pull out join condition contains other predicates") { | ||
| val udf = Substring("y.d".attr, 1, 5) | ||
| val originalQuery = x.join(y, condition = Option('a === udf && 'b > 'e)).select('a, 'e) | ||
| val correctAnswer = x.select('a, 'b, 'c) | ||
| .join(y.select('d, 'e, Alias(udf, udf.sql)()), | ||
| condition = Option('a === s"`${udf.sql}`".attr && 'b > 'e)).select('a, 'e) | ||
|
|
||
| comparePlans(Optimize.execute(originalQuery.analyze), correctAnswer.analyze) | ||
| } | ||
|
|
||
| test("Pull out EqualNullSafe join condition") { | ||
| val joinType = Inner | ||
| val udf = "x.b".attr + 1 | ||
| val coalesce1 = Coalesce(Seq(udf, Literal(0))) | ||
| val coalesce2 = Coalesce(Seq("y.e".attr, Literal(0))) | ||
| val isNull1 = IsNull(udf) | ||
| val isNull2 = IsNull("y.e".attr) | ||
|
|
||
| val originalQuery = x.join(y, joinType, Option(udf <=> 'e)).select('a, 'e) | ||
| val correctAnswer = | ||
| x.select('a, 'b, 'c, Alias(coalesce1, coalesce1.sql)(), Alias(isNull1, isNull1.sql)()) | ||
| .join(y.select('d, 'e, Alias(coalesce2, coalesce2.sql)(), Alias(isNull2, isNull2.sql)()), | ||
| condition = Option(s"`${coalesce1.sql}`".attr === s"`${coalesce2.sql}`".attr && | ||
| s"`${isNull1.sql}`".attr === s"`${isNull2.sql}`".attr)).select('a, 'e) | ||
|
|
||
| comparePlans(Optimize.execute(originalQuery.analyze), correctAnswer.analyze) | ||
| } | ||
|
|
||
| test("Negative case: non-equality join keys") { | ||
| val originalQuery = x.join(y, condition = Option("x.b".attr + 1 > 'e)).select('a, 'e) | ||
|
|
||
| comparePlans(Optimize.execute(originalQuery.analyze), originalQuery.analyze) | ||
| } | ||
|
|
||
| test("Negative case: all children are Attributes") { | ||
| val originalQuery = x.join(y, condition = Option('a === 'd)) | ||
|
|
||
| comparePlans(Optimize.execute(originalQuery.analyze), originalQuery.analyze) | ||
| } | ||
|
|
||
| test("Negative case: contains Literal") { | ||
| val originalQuery = x.join(y, condition = Option('a === "string")) | ||
|
|
||
| comparePlans(Optimize.execute(originalQuery.analyze), originalQuery.analyze) | ||
| } | ||
| } |
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -143,9 +143,10 @@ class WholeStageCodegenSuite extends QueryTest with SharedSparkSession | |
| val schema = new StructType().add("k", IntegerType).add("v", StringType) | ||
| val smallDF = spark.createDataFrame(rdd, schema) | ||
| val df = spark.range(10).join(broadcast(smallDF), col("k") === col("id")) | ||
| assert(df.queryExecution.executedPlan.find(p => | ||
| p.isInstanceOf[WholeStageCodegenExec] && | ||
| p.asInstanceOf[WholeStageCodegenExec].child.isInstanceOf[BroadcastHashJoinExec]).isDefined) | ||
| val broadcastHashJoin = df.queryExecution.executedPlan.find { | ||
| case WholeStageCodegenExec(ProjectExec(_, _: BroadcastHashJoinExec)) => true | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. wondering why we now need an extra project after join here? Can we remove it? The join seems not have complex key here.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is a |
||
| } | ||
| assert(broadcastHashJoin.isDefined) | ||
| assert(df.collect() === Array(Row(1, 1, "1"), Row(1, 1, "1"), Row(2, 2, "2"))) | ||
| } | ||
|
|
||
|
|
@@ -187,7 +188,7 @@ class WholeStageCodegenSuite extends QueryTest with SharedSparkSession | |
| // test one join with non-unique key from build side | ||
| val joinNonUniqueDF = df1.join(df2.hint("SHUFFLE_HASH"), $"k1" === $"k2" % 3, "full_outer") | ||
| assert(joinNonUniqueDF.queryExecution.executedPlan.collect { | ||
| case WholeStageCodegenExec(_ : ShuffledHashJoinExec) => true | ||
| case WholeStageCodegenExec(ProjectExec(_, _: ShuffledHashJoinExec)) => true | ||
| }.size === 1) | ||
| checkAnswer(joinNonUniqueDF, Seq(Row(0, 0), Row(0, 3), Row(0, 6), Row(0, 9), Row(1, 1), | ||
| Row(1, 4), Row(1, 7), Row(2, 2), Row(2, 5), Row(2, 8), Row(3, null), Row(4, null))) | ||
|
|
@@ -196,7 +197,7 @@ class WholeStageCodegenSuite extends QueryTest with SharedSparkSession | |
| val joinWithNonEquiDF = df1.join(df2.hint("SHUFFLE_HASH"), | ||
| $"k1" === $"k2" % 3 && $"k1" + 3 =!= $"k2", "full_outer") | ||
| assert(joinWithNonEquiDF.queryExecution.executedPlan.collect { | ||
| case WholeStageCodegenExec(_ : ShuffledHashJoinExec) => true | ||
| case WholeStageCodegenExec(ProjectExec(_, _: ShuffledHashJoinExec)) => true | ||
| }.size === 1) | ||
| checkAnswer(joinWithNonEquiDF, Seq(Row(0, 0), Row(0, 6), Row(0, 9), Row(1, 1), | ||
| Row(1, 7), Row(2, 2), Row(2, 8), Row(3, null), Row(4, null), Row(null, 3), Row(null, 4), | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks like a big problem. Can you investigate why we run python UDF 2 more times?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is because we will infer two
isnotnull(cast(pythonUDF0 as int)):Before this pr:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
OK, so it's because filter push down can lead to extra expression evaluation?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes. If we disable
spark.sql.constraintPropagation.enabled, the plan is:There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@wangyum @cloud-fan Seems we can just put the rule after
InferFiltersFromConstraints, and actually after theearlyScanPushDownRules. The python UDF test passed in my pr, see #36874.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think pull out has 3 advantages:
It has two disadvantage:
concat(col1, col2, col3, col4 ...).Personally, I think this rule is valuable. We have been using this rule for half a year.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can check if the poll out side can be broadcast so it should not be a blocker ?
This is really a trade-off, one conservative option may be: We only poll out the complex keys which the inside attribute is not the final output. So we can avoid the extra shuffle data as far as possible, for example:
And a config should be introduced for enable or disable easily.