Github user liancheng commented on a diff in the pull request:
https://github.com/apache/spark/pull/7446#discussion_r34957405
--- Diff:
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
---
@@ -512,20 +520,52 @@ object SimplifyFilters extends Rule[LogicalPlan] {
*
* This heuristic is valid assuming the expression evaluation cost is
minimal.
*/
-object PushPredicateThroughProject extends Rule[LogicalPlan] {
+object PushPredicateThroughProject extends Rule[LogicalPlan] with
PredicateHelper {
def apply(plan: LogicalPlan): LogicalPlan = plan transform {
case filter @ Filter(condition, project @ Project(fields, grandChild))
=>
- val sourceAliases = fields.collect { case a @ Alias(c, _) =>
- (a.toAttribute: Attribute) -> c
- }.toMap
- project.copy(child = filter.copy(
- replaceAlias(condition, sourceAliases),
- grandChild))
+ // Create a map of Aliases to their values from the child projection.
+ // e.g., 'SELECT a + b AS c, d ...' produces Map(c -> a + b).
+ val aliasMap = AttributeMap(fields.collect {
+ case a: Alias => (a.toAttribute, a.child)
+ })
+
+ // Split the condition into small conditions by `And`, so that we
can push down part of this
+ // condition without nondeterministic expressions.
+ val andConditions = splitConjunctivePredicates(condition)
+ val nondeterministicConditions =
andConditions.filter(hasNondeterministic(_, aliasMap))
+
+ // If there is no nondeterministic conditions, push down the whole
condition.
+ if (nondeterministicConditions.isEmpty) {
+ project.copy(child = Filter(replaceAlias(condition, aliasMap),
grandChild))
+ } else {
+ // If they are all nondeterministic conditions, leave it
un-changed.
+ if (nondeterministicConditions.length == andConditions.length) {
+ filter
+ } else {
+ val deterministicConditions =
andConditions.filterNot(hasNondeterministic(_, aliasMap))
+ // Push down the small conditions without nondeterministic
expressions.
+ val pushedCondition =
deterministicConditions.map(replaceAlias(_, aliasMap)).reduce(And)
+ Filter(nondeterministicConditions.reduce(And),
+ project.copy(child = Filter(pushedCondition, grandChild)))
+ }
+ }
+ }
+
+ private def hasNondeterministic(
+ condition: Expression,
+ sourceAliases: AttributeMap[Expression]) = {
+ condition.exists {
+ case a: Attribute =>
+
sourceAliases.get(a).map(_.exists(!_.deterministic)).getOrElse(false)
+ case _ => false
+ }
--- End diff --
Is there any reason why `Expression.deterministic` wasn't designed to be
recursive?
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]