Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
[SPARK-16475][SQL] Broadcast Hint for SQL Queries
  • Loading branch information
dongjoon-hyun committed Nov 3, 2016
commit 539782d93af14ed27c6f3a0fc659b13c4f92da41
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ querySpecification
(RECORDREADER recordReader=STRING)?
fromClause?
(WHERE where=booleanExpression)?)
| ((kind=SELECT setQuantifier? namedExpressionSeq fromClause?
| ((kind=SELECT hint? setQuantifier? namedExpressionSeq fromClause?
| fromClause (kind=SELECT setQuantifier? namedExpressionSeq)?)
lateralView*
(WHERE where=booleanExpression)?
Expand All @@ -373,6 +373,16 @@ querySpecification
windows?)
;

hint
: '/*+' hintStatement '*/'
;

hintStatement
: hintName=identifier
| hintName=identifier '(' parameters+=identifier parameters+=identifier ')'
Copy link
Contributor

Choose a reason for hiding this comment

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

why do we need this?

Copy link
Member

Choose a reason for hiding this comment

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

The purpose of this is to allow SqlBase.g4 accept more general rule for the future.
So, possibly, it's for reducing the change in SqlBase.g4 in order to add new hint rules.

Copy link
Member

Choose a reason for hiding this comment

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

This rule doesn't support like SELECT /*+ INDEX(a b c) */ * FROM t. To support it, it should be:

| hintName=identifier '(' parameters+=identifier parameters+=identifier* ')'

Is it intentional?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

What does it support?

INDEX(a, b, c)

?

I think ti's a bit weird to support space as the delimiter.

Copy link
Member

Choose a reason for hiding this comment

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

But we support INDEX(a b)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

do we? we should disallow it. want to submit a pr?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

btw this was written by @dongjoon-hyun. I didn't change it :)

Copy link
Member

Choose a reason for hiding this comment

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

ok. let me prepare a tiny one.

| hintName=identifier '(' parameters+=identifier (',' parameters+=identifier)* ')'
;

fromClause
: FROM relation (',' relation)* lateralView*
;
Expand Down Expand Up @@ -996,8 +1006,12 @@ SIMPLE_COMMENT
: '--' ~[\r\n]* '\r'? '\n'? -> channel(HIDDEN)
;

BRACKETED_EMPTY_COMMENT
: '/**/' -> channel(HIDDEN)
;

BRACKETED_COMMENT
: '/*' .*? '*/' -> channel(HIDDEN)
: '/*' ~[+] .*? '*/' -> channel(HIDDEN)
Copy link
Contributor

Choose a reason for hiding this comment

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

what does ~[+] mean?

Copy link
Member

Choose a reason for hiding this comment

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

It means except +.

Copy link
Member

Choose a reason for hiding this comment

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

/*+ is used hint rule in line 377.

;

WS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ class Analyzer(
CTESubstitution,
WindowsSubstitution,
EliminateUnions,
new SubstituteUnresolvedOrdinals(conf)),
new SubstituteUnresolvedOrdinals(conf),
SubstituteHints),
Batch("Resolution", fixedPoint,
ResolveTableValuedFunctions ::
ResolveRelations ::
Expand Down Expand Up @@ -1795,6 +1796,63 @@ class Analyzer(
}
}

/**
* Substitute Hints.
* - BROADCAST/BROADCASTJOIN/MAPJOIN match the closest table with the given name parameters.
*
* This rule substitutes `UnresolvedRelation`s in `Substitute` batch before `ResolveRelations`
* rule is applied. Here are two reasons.
* - To support `MetastoreRelation` in Hive module.
* - To reduce the effect of `Hint` on the other rules.
*
* After this rule, it is guaranteed that there exists no unknown `Hint` in the plan.
* All new `Hint`s should be transformed into concrete Hint classes `BroadcastHint` here.
*/
object SubstituteHints extends Rule[LogicalPlan] {
val BROADCAST_HINT_NAMES = Set("BROADCAST", "BROADCASTJOIN", "MAPJOIN")

import scala.collection.mutable.Set
private def appendAllDescendant(set: Set[LogicalPlan], plan: LogicalPlan): Unit = {
set += plan
plan.children.foreach { child => appendAllDescendant(set, child) }
}

def apply(plan: LogicalPlan): LogicalPlan = plan transform {
case logical: LogicalPlan => logical transformDown {
case h @ Hint(name, parameters, child) if BROADCAST_HINT_NAMES.contains(name.toUpperCase) =>
var resolvedChild = child
for (table <- parameters) {
var stop = false
val skipNodeSet = scala.collection.mutable.Set.empty[LogicalPlan]
resolvedChild = resolvedChild.transformDown {
case n if skipNodeSet.contains(n) =>
skipNodeSet -= n
n
case p @ Project(_, _) if p != resolvedChild =>
appendAllDescendant(skipNodeSet, p)
skipNodeSet -= p
p
case r @ BroadcastHint(UnresolvedRelation(t, _))
if !stop && resolver(t.table, table) =>
stop = true
r
case r @ UnresolvedRelation(t, alias) if !stop && resolver(t.table, table) =>
stop = true
if (alias.isDefined) {
SubqueryAlias(alias.get, BroadcastHint(r.copy(alias = None)), None)
} else {
BroadcastHint(r)
}
}
}
resolvedChild

// Remove unrecognized hints
case Hint(name, _, child) => child
}
}
}

/**
* Check and add proper window frames for all window functions.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,10 @@ trait CheckAnalysis extends PredicateHelper {
|in operator ${operator.simpleString}
""".stripMargin)

case Hint(_, _, _) =>
throw new IllegalStateException(
"logical hint operator should have been removed by analyzer")

case _ => // Analysis successful!
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,10 @@ class AstBuilder extends SqlBaseBaseVisitor[AnyRef] with Logging {
}

// Window
withDistinct.optionalMap(windows)(withWindows)
val withWindow = withDistinct.optionalMap(windows)(withWindows)

// Hint
withWindow.optionalMap(ctx.hint)(withHints)
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: we already import ctx._ at the beginning, to be consistent we can just write hint

}
}

Expand Down Expand Up @@ -527,6 +530,16 @@ class AstBuilder extends SqlBaseBaseVisitor[AnyRef] with Logging {
}
}

/**
* Add a Hint to a logical plan.
*/
private def withHints(
ctx: HintContext,
query: LogicalPlan): LogicalPlan = withOrigin(ctx) {
val stmt = ctx.hintStatement
Hint(stmt.hintName.getText, stmt.parameters.asScala.map(_.getText), query)
}

/**
* Add a [[Generate]] (Lateral View) to a logical plan.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,15 @@ case class BroadcastHint(child: LogicalPlan) extends UnaryNode {
override lazy val statistics: Statistics = super.statistics.copy(isBroadcastable = true)
}

/**
* A general hint for the child.
* A pair of (name, parameters).
*/
case class Hint(name: String, parameters: Seq[String], child: LogicalPlan) extends UnaryNode {
override lazy val resolved: Boolean = false
override def output: Seq[Attribute] = child.output
}

/**
* Options for writing new data into a table.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ trait AnalysisTest extends PlanTest {
val conf = new SimpleCatalystConf(caseSensitive)
val catalog = new SessionCatalog(new InMemoryCatalog, EmptyFunctionRegistry, conf)
catalog.createTempView("TaBlE", TestRelations.testRelation, overrideIfExists = true)
catalog.createTempView("TaBlE2", TestRelations.testRelation2, overrideIfExists = true)
new Analyzer(catalog, conf) {
override val extendedResolutionRules = EliminateSubqueryAliases :: Nil
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* 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.analysis

import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans._
import org.apache.spark.sql.catalyst.plans.logical._

class SubstituteHintsSuite extends AnalysisTest {
import org.apache.spark.sql.catalyst.analysis.TestRelations._

val a = testRelation.output(0)
val b = testRelation2.output(0)

test("case-sensitive or insensitive parameters") {
checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE"), table("TaBlE")),
BroadcastHint(testRelation),
caseSensitive = false)

checkAnalysis(
Hint("MAPJOIN", Seq("table"), table("TaBlE")),
BroadcastHint(testRelation),
caseSensitive = false)

checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE"), table("TaBlE")),
BroadcastHint(testRelation))

checkAnalysis(
Hint("MAPJOIN", Seq("table"), table("TaBlE")),
testRelation)
}

test("single hint") {
checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE"), table("TaBlE").select(a)),
BroadcastHint(testRelation).select(a))

checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE"), table("TaBlE").as("t").join(table("TaBlE2").as("u")).select(a)),
BroadcastHint(testRelation).join(testRelation2).select(a))

checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE2"),
table("TaBlE").as("t").join(table("TaBlE2").as("u")).select(a)),
testRelation.join(BroadcastHint(testRelation2)).select(a))
}

test("single hint with multiple parameters") {
checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE", "TaBlE"),
table("TaBlE").as("t").join(table("TaBlE2").as("u")).select(a)),
BroadcastHint(testRelation).join(testRelation2).select(a))

checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE", "TaBlE2"),
table("TaBlE").as("t").join(table("TaBlE2").as("u")).select(a)),
BroadcastHint(testRelation).join(BroadcastHint(testRelation2)).select(a))
}

test("duplicated nested hints are transformed into one") {
checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE"),
Hint("MAPJOIN", Seq("TaBlE"), table("TaBlE").as("t").select('a))
.join(table("TaBlE2").as("u")).select(a)),
BroadcastHint(testRelation).select(a).join(testRelation2).select(a))

checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE2"),
table("TaBlE").as("t").select(a)
.join(Hint("MAPJOIN", Seq("TaBlE2"), table("TaBlE2").as("u").select(b))).select(a)),
testRelation.select(a).join(BroadcastHint(testRelation2).select(b)).select(a))
}

test("distinct nested two hints are handled separately") {
checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE2"),
Hint("MAPJOIN", Seq("TaBlE"), table("TaBlE").as("t").select(a))
.join(table("TaBlE2").as("u")).select(a)),
BroadcastHint(testRelation).select(a).join(BroadcastHint(testRelation2)).select(a))

checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE"),
table("TaBlE").as("t")
.join(Hint("MAPJOIN", Seq("TaBlE2"), table("TaBlE2").as("u").select(b))).select(a)),
BroadcastHint(testRelation).join(BroadcastHint(testRelation2).select(b)).select(a))
}

test("deep self join") {
checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE"),
table("TaBlE").join(table("TaBlE")).join(table("TaBlE")).join(table("TaBlE")).select(a)),
BroadcastHint(testRelation).join(testRelation).join(testRelation).join(testRelation)
.select(a))
}

test("subquery should be ignored") {
checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE"),
table("TaBlE").select(a).as("x").join(table("TaBlE")).select(a)),
testRelation.select(a).join(BroadcastHint(testRelation)).select(a))

checkAnalysis(
Hint("MAPJOIN", Seq("TaBlE"),
table("TaBlE").as("t").select(a).as("x")
.join(table("TaBlE2").as("t2")).select(a)),
testRelation.select(a).join(testRelation2).select(a))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -503,4 +503,46 @@ class PlanParserSuite extends PlanTest {
assertEqual("select a, b from db.c where x !> 1",
table("db", "c").where('x <= 1).select('a, 'b))
}

test("select hint syntax") {
// Hive compatibility: Missing parameter raises ParseException.
val m = intercept[ParseException] {
parsePlan("SELECT /*+ HINT() */ * FROM t")
}.getMessage
assert(m.contains("no viable alternative at input"))

// Hive compatibility: No database.
val m2 = intercept[ParseException] {
parsePlan("SELECT /*+ MAPJOIN(default.t) */ * from default.t")
}.getMessage
assert(m2.contains("no viable alternative at input"))

comparePlans(
parsePlan("SELECT /*+ HINT */ * FROM t"),
Hint("HINT", Seq.empty, table("t").select(star())))

comparePlans(
parsePlan("SELECT /*+ BROADCASTJOIN(u) */ * FROM t"),
Hint("BROADCASTJOIN", Seq("u"), table("t").select(star())))

comparePlans(
parsePlan("SELECT /*+ MAPJOIN(u) */ * FROM t"),
Hint("MAPJOIN", Seq("u"), table("t").select(star())))

comparePlans(
parsePlan("SELECT /*+ STREAMTABLE(a,b,c) */ * FROM t"),
Hint("STREAMTABLE", Seq("a", "b", "c"), table("t").select(star())))

comparePlans(
parsePlan("SELECT /*+ INDEX(t emp_job_ix) */ * FROM t"),
Copy link
Contributor

Choose a reason for hiding this comment

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

what if users writing /*+ BROADCASTJOIN(a b) */? shall we treat it as /*+ BROADCASTJOIN(a, b) */?

Copy link
Member

Choose a reason for hiding this comment

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

Yes. Both are considered equally now.

Copy link
Member

Choose a reason for hiding this comment

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

@rxin Looks like we already support space as delimiter?

Hint("INDEX", Seq("t", "emp_job_ix"), table("t").select(star())))

comparePlans(
parsePlan("SELECT /*+ MAPJOIN(`default.t`) */ * from `default.t`"),
Hint("MAPJOIN", Seq("default.t"), table("default.t").select(star())))

comparePlans(
parsePlan("SELECT /*+ MAPJOIN(t) */ a from t where true group by a order by a"),
Hint("MAPJOIN", Seq("t"), table("t").where(Literal(true)).groupBy('a)('a)).orderBy('a.asc))
}
}
Loading