-
Notifications
You must be signed in to change notification settings - Fork 28.9k
[SPARK-11077] [SQL] Join elimination in Catalyst #9089
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
26 commits
Select commit
Hold shift + click to select a range
4f52877
Eliminate outer join before project
ankurdave ae46ab0
Use KeyHint to do join elimination
ankurdave df9ef14
Add foreign keys
ankurdave b22f702
Alias-aware join elimination + bugfixes
ankurdave 9072cb7
Propagate foreign keys through Join operator
ankurdave f430ea2
Remove key hints after join elimination
ankurdave 1302531
Support inner joins based on referential integrity
ankurdave 35949f5
Correctness fixes for join elimination
ankurdave 945e523
Do key hint resolution during analysis
ankurdave 504c9d8
Don't crash when foreign key refers to unresolved relation
ankurdave 83c8ff9
Fix JoinEliminationSuite
ankurdave 0b0b840
Merge remote-tracking branch 'apache-spark/master' into GraphFrames
ankurdave 9150dda
Fix KeyHintSuite after merge
ankurdave 873b322
In ForeignKey, store referencedRelation as logical plan
ankurdave 98e0b5e
Use semanticEquals for Attributes
ankurdave d43a2c0
Remove TODOs
ankurdave f4e7e01
Add more comments
ankurdave 49b196e
Merge remote-tracking branch 'apache-spark/master' into GraphFrames
ankurdave 578797c
Use SharedSQLContext in KeyHintSuite
ankurdave 7c7357b
Remove long URLs
ankurdave 5071759
Fix override of KeyHint#transformExpressions{Up,Down}
ankurdave ec2b80b
Declare new DataFrame methods extra-experimental
ankurdave 55bb135
Explain why we keep old keys in self-join rewrite
ankurdave e1ec23d
Revert "Fix override of KeyHint#transformExpressions{Up,Down}"
ankurdave 0cd8a91
Update transformExpressions override comments
ankurdave 5abceae
Merge remote-tracking branch 'apache-spark/master' into SPARK-11077-J…
ankurdave 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
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
183 changes: 183 additions & 0 deletions
183
...lyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joinEliminationPatterns.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,183 @@ | ||
| /* | ||
| * 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._ | ||
| import org.apache.spark.sql.catalyst.plans.logical._ | ||
|
|
||
| /** | ||
| * Finds left or right outer joins where only the outer table's columns are kept, and a key from the | ||
| * inner table is involved in the join so no duplicates would be generated. | ||
| */ | ||
| object CanEliminateUniqueKeyOuterJoin { | ||
| /** (outer, projectList) */ | ||
| type ReturnType = (LogicalPlan, Seq[NamedExpression]) | ||
|
|
||
| def unapply(plan: LogicalPlan): Option[ReturnType] = plan match { | ||
| case p @ Project(projectList, | ||
| ExtractEquiJoinKeys( | ||
| joinType @ (LeftOuter | RightOuter), leftJoinExprs, rightJoinExprs, _, left, right)) => | ||
| val (outer, inner, innerJoinExprs) = (joinType: @unchecked) match { | ||
| case LeftOuter => (left, right, rightJoinExprs) | ||
| case RightOuter => (right, left, leftJoinExprs) | ||
| } | ||
|
|
||
| val onlyOuterColsKept = AttributeSet(projectList).subsetOf(outer.outputSet) | ||
|
|
||
| val innerUniqueKeys = AttributeSet(inner.keys.collect { case UniqueKey(attr) => attr }) | ||
| val innerKeyIsInvolved = innerUniqueKeys.intersect(AttributeSet(innerJoinExprs)).nonEmpty | ||
|
|
||
| if (onlyOuterColsKept && innerKeyIsInvolved) { | ||
| Some((outer, projectList)) | ||
| } else { | ||
| None | ||
| } | ||
|
|
||
| case _ => None | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Finds joins based on foreign-key referential integrity, followed by [[Project]]s that reference | ||
| * no columns from the parent table other than the referenced unique keys. Such joins can be | ||
| * eliminated and replaced by the child table. | ||
| * | ||
| * The table containing the foreign key is referred to as the child table, while the table | ||
| * containing the referenced unique key is referred to as the parent table. | ||
| * | ||
| * For inner joins, all involved foreign keys must be non-nullable. | ||
| */ | ||
| object CanEliminateReferentialIntegrityJoin { | ||
| /** (parent, child, primaryForeignMap, projectList) */ | ||
| type ReturnType = | ||
| (LogicalPlan, LogicalPlan, AttributeMap[Attribute], Seq[NamedExpression]) | ||
|
|
||
| def unapply(plan: LogicalPlan): Option[ReturnType] = plan match { | ||
| case p @ Project(projectList, ExtractEquiJoinKeys( | ||
| joinType @ (Inner | LeftOuter | RightOuter), | ||
| leftJoinExprs, rightJoinExprs, _, left, right)) => | ||
| val innerJoin = joinType == Inner | ||
|
|
||
| val leftParentPFM = getPrimaryForeignMap(left, right, leftJoinExprs, rightJoinExprs) | ||
| val rightForeignKeysAreNonNullable = leftParentPFM.values.forall(!_.nullable) | ||
| val leftIsParent = | ||
| (leftParentPFM.nonEmpty && onlyPrimaryKeysKept(projectList, leftParentPFM, left) | ||
| && (!innerJoin || rightForeignKeysAreNonNullable)) | ||
|
|
||
| val rightParentPFM = getPrimaryForeignMap(right, left, rightJoinExprs, leftJoinExprs) | ||
| val leftForeignKeysAreNonNullable = rightParentPFM.values.forall(!_.nullable) | ||
| val rightIsParent = | ||
| (rightParentPFM.nonEmpty && onlyPrimaryKeysKept(projectList, rightParentPFM, right) | ||
| && (!innerJoin || leftForeignKeysAreNonNullable)) | ||
|
|
||
| if (leftIsParent) { | ||
| Some((left, right, leftParentPFM, projectList)) | ||
| } else if (rightIsParent) { | ||
| Some((right, left, rightParentPFM, projectList)) | ||
| } else { | ||
| None | ||
| } | ||
|
|
||
| case _ => None | ||
| } | ||
|
|
||
| /** | ||
| * Return a map where, for each PK=FK join expression based on referential integrity between | ||
| * `parent` and `child`, the unique key from `parent` is mapped to its corresponding foreign | ||
| * key from `child`. | ||
| */ | ||
| private def getPrimaryForeignMap( | ||
| parent: LogicalPlan, | ||
| child: LogicalPlan, | ||
| parentJoinExprs: Seq[Expression], | ||
| childJoinExprs: Seq[Expression]) | ||
| : AttributeMap[Attribute] = { | ||
| val primaryKeys = AttributeSet(parent.keys.collect { case UniqueKey(attr) => attr }) | ||
| val foreignKeys = new ForeignKeyFinder(child, parent) | ||
| AttributeMap(parentJoinExprs.zip(childJoinExprs).collect { | ||
| case (parentExpr: NamedExpression, childExpr: NamedExpression) | ||
| if primaryKeys.contains(parentExpr.toAttribute) | ||
| && foreignKeys.foreignKeyExists(childExpr.toAttribute, parentExpr.toAttribute) => | ||
| (parentExpr.toAttribute, childExpr.toAttribute) | ||
| }) | ||
| } | ||
|
|
||
| /** | ||
| * Return true if `kept` references no columns from `parent` except those involved in a PK=FK | ||
| * join expression. Such join expressions are stored in `primaryForeignMap`. | ||
| */ | ||
| private def onlyPrimaryKeysKept( | ||
| kept: Seq[NamedExpression], | ||
| primaryForeignMap: AttributeMap[Attribute], | ||
| parent: LogicalPlan) | ||
| : Boolean = { | ||
| AttributeSet(kept).forall { keptAttr => | ||
| if (parent.outputSet.contains(keptAttr)) { | ||
| primaryForeignMap.contains(keptAttr) | ||
| } else { | ||
| true | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private class ForeignKeyFinder(plan: LogicalPlan, referencedPlan: LogicalPlan) { | ||
| val equivalent = equivalences(referencedPlan) | ||
|
|
||
| def foreignKeyExists(attr: Attribute, referencedAttr: Attribute): Boolean = { | ||
| plan.keys.exists { | ||
| case ForeignKey(attr2, _, referencedAttr2) | ||
| if (attr semanticEquals attr2) | ||
| && equivalent.query(referencedAttr, referencedAttr2) => true | ||
| case _ => false | ||
| } | ||
| } | ||
|
|
||
| private def equivalences(plan: LogicalPlan): MutableDisjointAttributeSets = { | ||
| val s = new MutableDisjointAttributeSets | ||
| plan.collect { | ||
| case Project(projectList, _) => projectList.collect { | ||
| case a @ Alias(old: Attribute, _) => s.union(old, a.toAttribute) | ||
| } | ||
| } | ||
| s | ||
| } | ||
| } | ||
|
|
||
| private class MutableDisjointAttributeSets() { | ||
| private var sets = Set[AttributeSet]() | ||
| def add(x: Attribute): Unit = { | ||
| if (!sets.exists(_.contains(x))) { | ||
| sets += AttributeSet(x) | ||
| } | ||
| } | ||
| def union(x: Attribute, y: Attribute): Unit = { | ||
| add(x) | ||
| add(y) | ||
| val xSet = sets.find(_.contains(x)).get | ||
| val ySet = sets.find(_.contains(y)).get | ||
| sets -= xSet | ||
| sets -= ySet | ||
| sets += (xSet ++ ySet) | ||
| } | ||
| def query(x: Attribute, y: Attribute): Boolean = { | ||
| (x semanticEquals y) || sets.exists(s => s.contains(x) && s.contains(y)) | ||
| } | ||
| } |
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
Oops, something went wrong.
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.
Can't we just use
newKeyshere? Why do we need to keep old keys?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.
Good eye! This is to accommodate future self-joins. If we got rid of the old foreign keys, a future self-join would not recognize that the new keys applied to it, because the attributes would have been rewritten. I just added a comment noting this.
There's a unit test that covers this (fails if you remove the old keys).