Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 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 @@ -111,6 +111,7 @@ abstract class Optimizer(sessionCatalog: SessionCatalog)
ConstantPropagation,
FoldablePropagation,
OptimizeIn,
RewriteArithmeticFiltersOnIntOrLongColumn,
ConstantFolding,
ReorderAssociativeOperator,
LikeSimplification,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/*
* 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.plans.logical.{Filter, LogicalPlan}
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.types.{DataType, IntegerType, LongType}

/**
* Rewrite arithmetic filters on int or long column to its equivalent form,
* leaving attribute alone in one side, so that we can push it down to
* parquet or other file format.
Copy link
Member

@maropu maropu Mar 7, 2019

Choose a reason for hiding this comment

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

nit: how about this?

/**
 * Rewrite arithmetic filters on an integral-type (e.g., int and long) column to its equivalent
 * form, leaving attribute alone in a left side, so that we can push it down to
 * datasources (e.g., Parquet and ORC).
 *
 * For example, this rule can optimize a query as follows:
 * {{{
 *   SELECT * FROM table WHERE i + 3 = 5
 *   ==> SELECT * FROM table WHERE i = 5 - 3
 * }}}
 *
 * Then, the [[ConstantFolding]] rule will further optimize it as follows:
 * {{{
 *   SELECT * FROM table WHERE i = 2
 * }}}
 *
 * Note:
 * 1. This rule supports `Add` and `Subtract` in arithmetic expressions.
 * 2. This rule supports `=`, `>=`, `<=`, `>`, `<`, and `!=` in comparators.
 * 3. This rule supports `INT` and `LONG` types only. It doesn't support `FLOAT` or `DOUBLE`
 *    because of precision issues.
 */

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It's more clearly. I've updated it.

* For example, this rule can optimize
* {{{
* SELECT * FROM table WHERE i + 3 = 5
* }}}
* to
* {{{
* SELECT * FROM table WHERE i = 5 - 3
* }}}
* when i is Int or Long, and then other rules will further optimize it to
* {{{
* SELECT * FROM table WHERE i = 2
* }}}
* The arithmetic operation supports `Add` and `Subtract`. The comparision supports
* '=', '>=', '<=', '>', '<', '!='. It only supports type of `INT` and `LONG`,
* it doesn't support `FLOAT` or `DOUBLE` for precision issues.
*/
Copy link
Contributor

@SongYadong SongYadong Mar 6, 2019

Choose a reason for hiding this comment

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

It will be good to doc supported comparison operators here.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for your advice. I have updated the comments here

object RewriteArithmeticFiltersOnIntOrLongColumn extends Rule[LogicalPlan] with PredicateHelper {
Copy link
Member

Choose a reason for hiding this comment

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

Is this restrictive to Filter only? Looks like it rewrites all qualified expressions in all logical plan.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes, it is filter only. I've changed it to only work on Filter

def apply(plan: LogicalPlan): LogicalPlan = plan transform {
case f: Filter =>
f transformExpressionsUp {
case e @ BinaryComparison(left: BinaryArithmetic, right: Literal)
Copy link
Contributor

Choose a reason for hiding this comment

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

what about checking if it is foldable instead of a Literal?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes, foldable is better to accelerate convergence, I'll change it

if isDataTypeSafe(left.dataType) =>
transformLeft(e, left, right)
case e @ BinaryComparison(left: Literal, right: BinaryArithmetic)
if isDataTypeSafe(right.dataType) =>
transformRight(e, left, right)
}
}

private def transformLeft(
bc: BinaryComparison,
left: BinaryArithmetic,
right: Literal): Expression = {
left match {
case Add(ar: AttributeReference, lit: Literal) if isOptSafe(Subtract(right, lit)) =>
bc.makeCopy(Array(ar, Subtract(right, lit)))
case Add(lit: Literal, ar: AttributeReference) if isOptSafe(Subtract(right, lit)) =>
bc.makeCopy(Array(ar, Subtract(right, lit)))
case Subtract(ar: AttributeReference, lit: Literal) if isOptSafe(Add(right, lit)) =>
bc.makeCopy(Array(ar, Add(right, lit)))
case Subtract(lit: Literal, ar: AttributeReference) if isOptSafe(Subtract(lit, right)) =>
bc.makeCopy(Array(Subtract(lit, right), ar))
case _ => bc
}
}

private def transformRight(
bc: BinaryComparison,
left: Literal,
right: BinaryArithmetic): Expression = {
right match {
case Add(ar: AttributeReference, lit: Literal) if isOptSafe(Subtract(left, lit)) =>
bc.makeCopy(Array(Subtract(left, lit), ar))
case Add(lit: Literal, ar: AttributeReference) if isOptSafe(Subtract(left, lit)) =>
bc.makeCopy(Array(Subtract(left, lit), ar))
case Subtract(ar: AttributeReference, lit: Literal) if isOptSafe(Add(left, lit)) =>
bc.makeCopy(Array(Add(left, lit), ar))
case Subtract(lit: Literal, ar: AttributeReference) if isOptSafe(Subtract(lit, left)) =>
bc.makeCopy(Array(ar, Subtract(lit, left)))
case _ => bc
}
}

private def isDataTypeSafe(dataType: DataType): Boolean = dataType match {
Copy link
Contributor

Choose a reason for hiding this comment

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

why only integer and longs are accepted?

Copy link
Contributor Author

@WangGuangxin WangGuangxin Mar 7, 2019

Choose a reason for hiding this comment

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

Float and Double has precision issues. For example, a + 3.2 < 4.0 will be convert to a < 0.7999999999999998.

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 the other integral types, e.g., short?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes, integral types(byte, short, int, long) are all ok. I'll add support for byte and short type as well.

Copy link
Contributor

Choose a reason for hiding this comment

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

I think the precision issue would be there anyway, when executed at runtime, am I wrong?

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 think the precision issue would be there anyway, when executed at runtime, am I wrong?

I have a simple test on a table with a Double type column a, it has two records: 0.7999999999999998 and 0.8
image

with a + 3.2 = 4.0, it returns both two records. But if we optimized it to a = 0.7999999999999998, the result will be wrong

Copy link
Contributor

Choose a reason for hiding this comment

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

Here is an example:

scala> spark.sql("select float(1E-8) + float(1E+10) <= float(1E+10)").show()
+----------------------------------------------------------------------+
|((CAST(1E-8 AS FLOAT) + CAST(1E+10 AS FLOAT)) <= CAST(1E+10 AS FLOAT))|
+----------------------------------------------------------------------+
|                                                                  true|
+----------------------------------------------------------------------+


scala> spark.sql("select float(1E-8) <= float(1E+10) - float(1E+10)").show()
+----------------------------------------------------------------------+
|(CAST(1E-8 AS FLOAT) <= (CAST(1E+10 AS FLOAT) - CAST(1E+10 AS FLOAT)))|
+----------------------------------------------------------------------+
|                                                                 false|
+----------------------------------------------------------------------+

Although float(1E-8) + float(1E+10) <= float(1E+10) should return false. This may lead to inconsistency.

Copy link
Contributor

Choose a reason for hiding this comment

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

thanks for the explanation

case IntegerType | LongType => true
case _ => false
}

private def isOptSafe(e: BinaryArithmetic): Boolean = {
val leftVal = e.left.eval(EmptyRow)
val rightVal = e.right.eval(EmptyRow)

e match {
case Add(_: Literal, _: Literal) =>
e.dataType match {
case IntegerType =>
isAddSafe(leftVal, rightVal, Int.MinValue, Int.MaxValue)
case LongType =>
isAddSafe(leftVal, rightVal, Long.MinValue, Long.MaxValue)
case _ => false
}

case Subtract(_: Literal, _: Literal) =>
e.dataType match {
case IntegerType =>
isSubtractSafe(leftVal, rightVal, Int.MinValue, Int.MaxValue)
case LongType =>
isSubtractSafe(leftVal, rightVal, Long.MinValue, Long.MaxValue)
case _ => false
}

case _ => false
}
}

private def isAddSafe[T](left: Any, right: Any, minValue: T, maxValue: T)(
implicit num: Numeric[T]): Boolean = {
import num._
val leftVal = left.asInstanceOf[T]
val rightVal = right.asInstanceOf[T]
if (rightVal > zero) {
leftVal <= maxValue - rightVal
} else {
leftVal >= minValue - rightVal
}
}

private def isSubtractSafe[T](left: Any, right: Any, minValue: T, maxValue: T)(
implicit num: Numeric[T]): Boolean = {
import num._
val leftVal = left.asInstanceOf[T]
val rightVal = right.asInstanceOf[T]
if (rightVal > zero) {
leftVal >= minValue + rightVal
} else {
leftVal <= maxValue + rightVal
}
}
}
Loading