Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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 @@ -539,17 +539,22 @@ object LimitPushDown extends Rule[LogicalPlan] {
// pushdown Limit.
case LocalLimit(exp, u: Union) =>
LocalLimit(exp, u.copy(children = u.children.map(maybePushLocalLimit(exp, _))))
// Add extra limits below OUTER JOIN. For LEFT OUTER and RIGHT OUTER JOIN we push limits to
// the left and right sides, respectively. It's not safe to push limits below FULL OUTER
// JOIN in the general case without a more invasive rewrite.
// Add extra limits below JOIN. For LEFT OUTER and RIGHT OUTER JOIN we push limits to
// the left and right sides, respectively. For INNER and CROSS JOIN we push limits to
// both the left and right sides if join condition is empty. It's not safe to push limits
// below FULL OUTER JOIN in the general case without a more invasive rewrite.
// We also need to ensure that this limit pushdown rule will not eventually introduce limits
// on both sides if it is applied multiple times. Therefore:
// - If one side is already limited, stack another limit on top if the new limit is smaller.
// The redundant limit will be collapsed by the CombineLimits rule.
case LocalLimit(exp, join @ Join(left, right, joinType, _, _)) =>
case LocalLimit(exp, join @ Join(left, right, joinType, conditionOpt, _)) =>
val newJoin = joinType match {
case RightOuter => join.copy(right = maybePushLocalLimit(exp, right))
case LeftOuter => join.copy(left = maybePushLocalLimit(exp, left))
Copy link
Contributor

Choose a reason for hiding this comment

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

It seems that we can also push down limit into left side, for LEFT SEMI and LEFT ANTI join, right?
I can create a minor PR if it's not on your plan @wangyum , thanks.

Copy link
Member Author

Choose a reason for hiding this comment

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

It seems we can not pushdown LEFT SEMI JOIN, for example:

spark.range(20).selectExpr("id % 10 as id").repartition(1).write.saveAsTable("t1")
spark.range(5, 9, 1).repartition(1).write.saveAsTable("t2")
val df = spark.sql("select * from t1 LEFT SEMI JOIN t2 on t1.id = t2.id limit 3")
df.explain()
df.show

Current:

== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- CollectLimit 3
   +- BroadcastHashJoin [id#10L], [id#11L], LeftSemi, BuildRight, false
      :- Filter isnotnull(id#10L)
      :  +- FileScan parquet default.t1[id#10L] Batched: true, DataFilters: [isnotnull(id#10L)], Format: Parquet, Location: InMemoryFileIndex(1 paths)[file:/Users/yumwang/spark/SPARK-28169/spark-warehouse/org.apache.spark..., PartitionFilters: [], PushedFilters: [IsNotNull(id)], ReadSchema: struct<id:bigint>
      +- BroadcastExchange HashedRelationBroadcastMode(List(input[0, bigint, false]),false), [id=#69]
         +- Filter isnotnull(id#11L)
            +- FileScan parquet default.t2[id#11L] Batched: true, DataFilters: [isnotnull(id#11L)], Format: Parquet, Location: InMemoryFileIndex(1 paths)[file:/Users/yumwang/spark/SPARK-28169/spark-warehouse/org.apache.spark..., PartitionFilters: [], PushedFilters: [IsNotNull(id)], ReadSchema: struct<id:bigint>


+---+
| id|
+---+
|  5|
|  6|
|  7|
+---+

Pushdown:

== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- CollectLimit 3
   +- BroadcastHashJoin [id#10L], [id#11L], LeftSemi, BuildRight, false
      :- LocalLimit 3
      :  +- Filter isnotnull(id#10L)
      :     +- LocalLimit 3
      :        +- FileScan parquet default.t1[id#10L] Batched: true, DataFilters: [], Format: Parquet, Location: InMemoryFileIndex(1 paths)[file:/Users/yumwang/spark/SPARK-28169/spark-warehouse/org.apache.spark..., PartitionFilters: [], PushedFilters: [], ReadSchema: struct<id:bigint>
      +- BroadcastExchange HashedRelationBroadcastMode(List(input[0, bigint, false]),false), [id=#77]
         +- Filter isnotnull(id#11L)
            +- FileScan parquet default.t2[id#11L] Batched: true, DataFilters: [isnotnull(id#11L)], Format: Parquet, Location: InMemoryFileIndex(1 paths)[file:/Users/yumwang/spark/SPARK-28169/spark-warehouse/org.apache.spark..., PartitionFilters: [], PushedFilters: [IsNotNull(id)], ReadSchema: struct<id:bigint>


+---+
| id|
+---+
+---+

Copy link
Contributor

Choose a reason for hiding this comment

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

@wangyum - yes, you are right. My bad. LEFT OUTER/RIGHT OUTER join will output the left/right side rows anyway no matter of being matched or not. So they are safe for limit push down, but not LEFT SEMI/LEFT ANTI.

Copy link
Contributor

Choose a reason for hiding this comment

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

Actually, what about LEFT SEMI / LEFT ANTI join without condition? They should be planned into physical operator BroadcastNestedLoopJoin instead.

case _: InnerLike if conditionOpt.isEmpty =>
join.copy(
left = maybePushLocalLimit(exp, left),
right = maybePushLocalLimit(exp, right))
case _ => join
}
LocalLimit(exp, newJoin)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import org.apache.spark.sql.catalyst.analysis.EliminateSubqueryAliases
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans._
import org.apache.spark.sql.catalyst.expressions.Add
import org.apache.spark.sql.catalyst.plans.{FullOuter, LeftOuter, PlanTest, RightOuter}
import org.apache.spark.sql.catalyst.plans.{Cross, FullOuter, Inner, LeftOuter, PlanTest, RightOuter}
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.rules._

Expand Down Expand Up @@ -194,4 +194,22 @@ class LimitPushdownSuite extends PlanTest {
LocalLimit(1, y.groupBy(Symbol("b"))(count(1))))).analyze
comparePlans(expected2, optimized2)
}

test("SPARK-26138: pushdown limit through InnerLike when condition is empty") {
Copy link
Member

Choose a reason for hiding this comment

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

Shall we have a e2e test to check answer too?

Seq(Cross, Inner).foreach { joinType =>
val originalQuery = x.join(y, joinType).limit(1)
val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer = Limit(1, LocalLimit(1, x).join(LocalLimit(1, y), joinType)).analyze
comparePlans(optimized, correctAnswer)
}
}

test("SPARK-26138: Should not pushdown limit through InnerLike when condition is not empty") {
Seq(Cross, Inner).foreach { joinType =>
val originalQuery = x.join(y, joinType, Some("x.a".attr === "y.b".attr)).limit(1)
val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer = Limit(1, x.join(y, joinType, Some("x.a".attr === "y.b".attr))).analyze
comparePlans(optimized, correctAnswer)
}
}
}
17 changes: 15 additions & 2 deletions sql/core/src/test/scala/org/apache/spark/sql/SQLQuerySuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ import org.apache.spark.scheduler.{SparkListener, SparkListenerJobStart}
import org.apache.spark.sql.catalyst.expressions.GenericRow
import org.apache.spark.sql.catalyst.expressions.aggregate.{Complete, Partial}
import org.apache.spark.sql.catalyst.optimizer.{ConvertToLocalRelation, NestedColumnAliasingSuite}
import org.apache.spark.sql.catalyst.plans.logical.{Project, RepartitionByExpression}
import org.apache.spark.sql.catalyst.plans.logical.{LocalLimit, Project, RepartitionByExpression}
import org.apache.spark.sql.catalyst.util.StringUtils
import org.apache.spark.sql.execution.UnionExec
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
import org.apache.spark.sql.execution.aggregate.{HashAggregateExec, ObjectHashAggregateExec, SortAggregateExec}
import org.apache.spark.sql.execution.columnar.InMemoryTableScanExec
import org.apache.spark.sql.execution.command.FunctionsCommand
import org.apache.spark.sql.execution.datasources.SchemaColumnConvertNotSupportedException
import org.apache.spark.sql.execution.datasources.{LogicalRelation, SchemaColumnConvertNotSupportedException}
import org.apache.spark.sql.execution.datasources.v2.BatchScanExec
import org.apache.spark.sql.execution.datasources.v2.orc.OrcScan
import org.apache.spark.sql.execution.datasources.v2.parquet.ParquetScan
Expand Down Expand Up @@ -4021,6 +4021,19 @@ class SQLQuerySuite extends QueryTest with SharedSparkSession with AdaptiveSpark
}
}
}

test("SPARK-26138 Pushdown limit through InnerLike when condition is empty") {
withTable("t1", "t2") {
spark.range(5).repartition(1).write.saveAsTable("t1")
spark.range(5).repartition(1).write.saveAsTable("t2")
val df = spark.sql("SELECT * FROM t1 CROSS JOIN t2 LIMIT 3")
val pushedLocalLimits = df.queryExecution.optimizedPlan.collect {
case l @ LocalLimit(_, _: LogicalRelation) => l
}
assert(pushedLocalLimits.length === 2)
checkAnswer(df, Row(0, 0) :: Row(0, 1) :: Row(0, 2) :: Nil)
}
}
}

case class Foo(bar: Option[String])