Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ abstract class Optimizer(sessionCatalog: SessionCatalog)
PushProjectionThroughUnion,
ReorderJoin,
EliminateOuterJoin,
EliminateCrossJoin,
InferFiltersFromConstraints,
BooleanSimplification,
PushPredicateThroughJoin,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,99 @@ object EliminateOuterJoin extends Rule[LogicalPlan] with PredicateHelper {
if (j.joinType == newJoinType) f else Filter(condition, j.copy(joinType = newJoinType))
}
}

/**
* A rule that eliminates CROSS joins by inferring join conditions from propagated constraints.
*
* The optimization is applicable only to CROSS joins. For other join types, adding inferred join
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we apply this optimization to all joins after #19054?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It sounds promising.

* conditions would potentially shuffle children as child node's partitioning won't satisfy the JOIN
* node's requirements which otherwise could have.
*
* For instance, if there is a CROSS join, where the left relation has 'a = 1' and the right
* relation has 'b = 1', the rule infers 'a = b' as a join predicate.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For instance, given a CROSS join with the constraint 'a = 1' from the left child and the constraint 'b = 1' from the right child, this rule infers a new join predicate 'a = b' and convert it to an Inner join.

*/
object EliminateCrossJoin extends Rule[LogicalPlan] with PredicateHelper {

def apply(plan: LogicalPlan): LogicalPlan = {
if (SQLConf.get.constraintPropagationEnabled) {
eliminateCrossJoin(plan)
} else {
plan
}
}

private def eliminateCrossJoin(plan: LogicalPlan): LogicalPlan = plan transform {
case join@Join(leftPlan, rightPlan, Cross, None) =>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: join@Join -> join @ Join

val leftConstraints = join.constraints.filter(_.references.subsetOf(leftPlan.outputSet))
val rightConstraints = join.constraints.filter(_.references.subsetOf(rightPlan.outputSet))
val inferredJoinPredicates = inferJoinPredicates(leftConstraints, rightConstraints)
val joinConditionOpt = inferredJoinPredicates.reduceOption(And)
if (joinConditionOpt.isDefined) Join(leftPlan, rightPlan, Inner, joinConditionOpt) else join
}

private def inferJoinPredicates(
leftConstraints: Set[Expression],
rightConstraints: Set[Expression]): Set[EqualTo] = {

// iterate through the left constraints and build a hash map that points semantically
// equivalent expressions into attributes
val emptyEquivalenceMap = Map.empty[SemanticExpression, Set[Attribute]]
val equivalenceMap = leftConstraints.foldLeft(emptyEquivalenceMap) { case (map, constraint) =>
constraint match {
case EqualTo(attr: Attribute, expr: Expression) =>
updateEquivalenceMap(map, attr, expr)
case EqualTo(expr: Expression, attr: Attribute) =>
updateEquivalenceMap(map, attr, expr)
case _ => map
}
}

// iterate through the right constraints and infer join conditions using the equivalence map
rightConstraints.foldLeft(Set.empty[EqualTo]) { case (joinConditions, constraint) =>
constraint match {
case EqualTo(attr: Attribute, expr: Expression) =>
appendJoinConditions(attr, expr, equivalenceMap, joinConditions)
case EqualTo(expr: Expression, attr: Attribute) =>
appendJoinConditions(attr, expr, equivalenceMap, joinConditions)
case _ => joinConditions
}
}
}

private def updateEquivalenceMap(
equivalenceMap: Map[SemanticExpression, Set[Attribute]],
attr: Attribute,
expr: Expression): Map[SemanticExpression, Set[Attribute]] = {

val equivalentAttrs = equivalenceMap.getOrElse(expr, Set.empty[Attribute])
if (equivalentAttrs.contains(attr)) {
equivalenceMap
} else {
equivalenceMap.updated(expr, equivalentAttrs + attr)
}
}

private def appendJoinConditions(
attr: Attribute,
expr: Expression,
equivalenceMap: Map[SemanticExpression, Set[Attribute]],
joinConditions: Set[EqualTo]): Set[EqualTo] = {

equivalenceMap.get(expr) match {
case Some(equivalentAttrs) => joinConditions ++ equivalentAttrs.map(EqualTo(attr, _))
case None => joinConditions
}
}

// the purpose of this class is to treat 'a === 1 and 1 === 'a as the same expressions
implicit class SemanticExpression(private val expr: Expression) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we reuse EquivalentExpressions? You can search the code base and see how the others use it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gatorsmile

I think we just need the case class inside EquivalentExpressions since we have to map all semantically equivalent expressions into a set of attributes (as opposed to mapping an expression into a set of equivalent expressions).

I see two ways to go:

  1. Expose the case class inside EquivalentExpressions with minimum changes in the code base (e.g., using a companion object):
object EquivalentExpressions {

  /**
   * Wrapper around an Expression that provides semantic equality.
   */
  implicit class SemanticExpr(private val e: Expression) {
    override def equals(o: Any): Boolean = o match {
      case other: SemanticExpr => e.semanticEquals(other.e)
      case _ => false
    }

    override def hashCode: Int = e.semanticHash()
  }
}
  1. Keep EquivalentExpressions as it is and maintain a separate map from expressions to attributes in the proposed rule.

Personally, I lean toward the first idea since it might be useful to have SemanticExpr alone. However, there can be other drawbacks that did not come into my mind.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about building a new class to process all the cases similar to this one?

An Attribute is also an Expression. Basically, the internal will be still a hash map mutable.HashMap.empty[SemanticEqualExpr, mutable.MutableList[Expression]]

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using a Set instead of a List might be beneficial in the proposed rule. What about the following?

class EquivalentExpressionMap {

  private val equivalenceMap = mutable.HashMap.empty[SemanticallyEqualExpr, mutable.Set[Expression]]

  def put(expression: Expression, equivalentExpression: Expression): Unit = {
    val equivalentExpressions = equivalenceMap.getOrElse(expression, mutable.Set.empty)
    if (!equivalentExpressions.contains(equivalentExpression)) {
      equivalenceMap(expression) = equivalentExpressions += equivalentExpression
    }
  }
  
  // produce an immutable copy to avoid any modifications from outside
  def get(expression: Expression): Set[Expression] =
    equivalenceMap.get(expression).fold(Set.empty[Expression])(_.toSet)

}

object EquivalentExpressionMap {

  private implicit class SemanticallyEqualExpr(private val expr: Expression) {
    override def equals(o: Any): Boolean = o match {
      case other: SemanticallyEqualExpr => expr.semanticEquals(other.expr)
      case _ => false
    }

    override def hashCode: Int = expr.semanticHash()
  }
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did not check it carefully, but how about ExpressionSet?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am afraid ExpressionSet will not help here since we need to map a semantically equivalent expression into a set of attributes that correspond to it. It is not enough to check if there is an equivalent expression. Therefore, EquivalentExpressions and ExpressionSet are not applicable (as far as I see).

EquivalentExpressionMap from the previous comment assumes the following workflow:

val equivalentExressionMap = new EquivalentExpressionMap
...
equivalentExressionMap.put(1 * 2, t1.a)
equivalentExressionMap.put(3, t1.b)
...
equivalentExressionMap.get(1 * 2) // Set(t1.a)
equivalentExressionMap.get(2 * 1) // Set(t1.a)

Copy link
Member

@gatorsmile gatorsmile Nov 28, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean using ExpressionSet in EquivalentExpressionMap

private val equivalenceMap = mutable.HashMap.empty[SemanticallyEqualExpr, ExpressionSet]

def get(expression: Expression): Set[Expression]

def put(expression: Expression, equivalentExpression: Expression): Unit


override def hashCode(): Int = expr.semanticHash()

override def equals(other: Any): Boolean = other match {
case other: SemanticExpression => expr.semanticEquals(other.expr)
case _ => false
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
/*
* 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.{Cast, Expression, Literal, Not}
import org.apache.spark.sql.catalyst.plans.{Cross, Inner, JoinType, PlanTest}
import org.apache.spark.sql.catalyst.plans.logical.{LocalRelation, LogicalPlan}
import org.apache.spark.sql.catalyst.rules.RuleExecutor
import org.apache.spark.sql.internal.SQLConf.CONSTRAINT_PROPAGATION_ENABLED
import org.apache.spark.sql.types.IntegerType

class EliminateCrossJoinSuite extends PlanTest {

object Optimize extends RuleExecutor[LogicalPlan] {
val batches =
Batch("Eliminate cross joins", FixedPoint(10),
EliminateCrossJoin,
PushPredicateThroughJoin) :: Nil
}

val testRelation1 = LocalRelation('a.int, 'b.int)
val testRelation2 = LocalRelation('c.int, 'd.int)

test("successful elimination of cross joins (1)") {
checkJoinOptimization(
originalFilter = 'a === 1 && 'c === 1 && 'd === 1,
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = 'a === 1,
expectedRightRelationFilter = 'c === 1 && 'd === 1,
expectedJoinType = Inner,
expectedJoinCondition = Some('a === 'c && 'a === 'd))
}

test("successful elimination of cross joins (2)") {
checkJoinOptimization(
originalFilter = 'a === 1 && 'b === 2 && 'd === 1,
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = 'a === 1 && 'b === 2,
expectedRightRelationFilter = 'd === 1,
expectedJoinType = Inner,
expectedJoinCondition = Some('a === 'd))
}

test("successful elimination of cross joins (3)") {
// PushPredicateThroughJoin will push 'd === 'a into the join condition
// EliminateCrossJoin will NOT apply because the condition will be already present
// therefore, the join type will stay the same (i.e., CROSS)
checkJoinOptimization(
originalFilter = 'a === 1 && Literal(1) === 'd && 'd === 'a,
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = 'a === 1,
expectedRightRelationFilter = Literal(1) === 'd,
expectedJoinType = Cross,
expectedJoinCondition = Some('a === 'd))
}

test("successful elimination of cross joins (4)") {
// Literal(1) * Literal(2) and Literal(2) * Literal(1) are semantically equal
checkJoinOptimization(
originalFilter = 'a === Literal(1) * Literal(2) && Literal(2) * Literal(1) === 'c,
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = 'a === Literal(1) * Literal(2),
expectedRightRelationFilter = Literal(2) * Literal(1) === 'c,
expectedJoinType = Inner,
expectedJoinCondition = Some('a === 'c))
}

test("successful elimination of cross joins (5)") {
checkJoinOptimization(
originalFilter = 'a === 1 && Literal(1) === 'a && 'c === 1,
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = 'a === 1 && Literal(1) === 'a,
expectedRightRelationFilter = 'c === 1,
expectedJoinType = Inner,
expectedJoinCondition = Some('a === 'c))
}

test("successful elimination of cross joins (6)") {
checkJoinOptimization(
originalFilter = 'a === Cast("1", IntegerType) && 'c === Cast("1", IntegerType) && 'd === 1,
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = 'a === Cast("1", IntegerType),
expectedRightRelationFilter = 'c === Cast("1", IntegerType) && 'd === 1,
expectedJoinType = Inner,
expectedJoinCondition = Some('a === 'c))
}

test("successful elimination of cross joins (7)") {
// The join condition appears due to PushPredicateThroughJoin
checkJoinOptimization(
originalFilter = (('a >= 1 && 'c === 1) || 'd === 10) && 'b === 10 && 'c === 1,
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = 'b === 10,
expectedRightRelationFilter = 'c === 1,
expectedJoinType = Cross,
expectedJoinCondition = Some(('a >= 1 && 'c === 1) || 'd === 10))
}

test("successful elimination of cross joins (8)") {
checkJoinOptimization(
originalFilter = 'a === 1 && 'c === 1 && Literal(1) === 'a && Literal(1) === 'c,
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = 'a === 1 && Literal(1) === 'a,
expectedRightRelationFilter = 'c === 1 && Literal(1) === 'c,
expectedJoinType = Inner,
expectedJoinCondition = Some('a === 'c))
}

test("inability to detect join conditions when constant propagation is disabled") {
withSQLConf(CONSTRAINT_PROPAGATION_ENABLED.key -> "false") {
checkJoinOptimization(
originalFilter = 'a === 1 && 'c === 1 && 'd === 1,
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = 'a === 1,
expectedRightRelationFilter = 'c === 1 && 'd === 1,
expectedJoinType = Cross,
expectedJoinCondition = None)
}
}

test("inability to detect join conditions (1)") {
checkJoinOptimization(
originalFilter = 'a >= 1 && 'c === 1 && 'd >= 1,
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = 'a >= 1,
expectedRightRelationFilter = 'c === 1 && 'd >= 1,
expectedJoinType = Cross,
expectedJoinCondition = None)
}

test("inability to detect join conditions (2)") {
checkJoinOptimization(
originalFilter = Literal(1) === 'b && ('c === 1 || 'd === 1),
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = Literal(1) === 'b,
expectedRightRelationFilter = 'c === 1 || 'd === 1,
expectedJoinType = Cross,
expectedJoinCondition = None)
}

test("inability to detect join conditions (3)") {
checkJoinOptimization(
originalFilter = Literal(1) === 'b && 'c === 1,
originalJoinType = Cross,
originalJoinCondition = Some('c === 'b),
expectedLeftRelationFilter = Literal(1) === 'b,
expectedRightRelationFilter = 'c === 1,
expectedJoinType = Cross,
expectedJoinCondition = Some('c === 'b))
}

test("inability to detect join conditions (4)") {
checkJoinOptimization(
originalFilter = Not('a === 1) && 'd === 1,
originalJoinType = Cross,
originalJoinCondition = None,
expectedLeftRelationFilter = Not('a === 1),
expectedRightRelationFilter = 'd === 1,
expectedJoinType = Cross,
expectedJoinCondition = None)
}

private def checkJoinOptimization(
originalFilter: Expression,
originalJoinType: JoinType,
originalJoinCondition: Option[Expression],
expectedLeftRelationFilter: Expression,
expectedRightRelationFilter: Expression,
expectedJoinType: JoinType,
expectedJoinCondition: Option[Expression]): Unit = {

val originalQuery = testRelation1
.join(testRelation2, originalJoinType, originalJoinCondition)
.where(originalFilter)
val optimizedQuery = Optimize.execute(originalQuery.analyze)

val left = testRelation1.where(expectedLeftRelationFilter)
val right = testRelation2.where(expectedRightRelationFilter)
val expectedQuery = left.join(right, expectedJoinType, expectedJoinCondition).analyze
comparePlans(optimizedQuery, expectedQuery)
}
}