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 @@ -48,7 +48,11 @@ object SimplifyExtractValueOps extends Rule[LogicalPlan] {
// `$"struct_col".withField("b", lit(1)).withField("b", lit(2)).getField("b")`
// we want to return `lit(2)` (and not `lit(1)`).
val expr = matches.last._2
If(IsNull(struct), Literal(null, expr.dataType), expr)
if (struct.nullable) {
If(IsNull(struct), Literal(null, expr.dataType), expr)
} else {
expr
}
} else {
GetStructField(struct, ordinal, maybeName)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ abstract class Optimizer(catalogManager: CatalogManager)
RemoveRedundantAliases,
UnwrapCastInBinaryComparison,
RemoveNoopOperators,
CombineWithFields,
OptimizeWithFields,
SimplifyExtractValueOps,
CombineConcats) ++
extendedOperatorOptimizationRules
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,49 @@

package org.apache.spark.sql.catalyst.optimizer

import org.apache.spark.sql.catalyst.expressions.WithFields
import java.util.Locale

import scala.collection.mutable

import org.apache.spark.sql.catalyst.expressions.{Expression, WithFields}
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.internal.SQLConf


/**
* Combines all adjacent [[WithFields]] expression into a single [[WithFields]] expression.
* Optimizes [[WithFields]] expression chains.
*/
object CombineWithFields extends Rule[LogicalPlan] {
object OptimizeWithFields extends Rule[LogicalPlan] {
def apply(plan: LogicalPlan): LogicalPlan = plan transformAllExpressions {
case WithFields(structExpr, names, values)
if names.map(_.toLowerCase(Locale.ROOT)).distinct.length != names.length =>
val caseSensitive = SQLConf.get.caseSensitiveAnalysis

val newNames = mutable.ArrayBuffer.empty[String]
val newValues = mutable.ArrayBuffer.empty[Expression]

if (caseSensitive) {
names.zip(values).reverse.foreach { case (name, value) =>
if (!newNames.contains(name)) {
newNames += name
newValues += value
}
}
} else {
val nameSet = mutable.HashSet.empty[String]
names.zip(values).reverse.foreach { case (name, value) =>
val lowercaseName = name.toLowerCase(Locale.ROOT)
if (!nameSet.contains(lowercaseName)) {
newNames += name
newValues += value
nameSet += lowercaseName
}
}
}

WithFields(structExpr, names = newNames.reverse.toSeq, valExprs = newValues.reverse.toSeq)
Copy link
Contributor

Choose a reason for hiding this comment

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

For my understanding, can you explain how we expect to benefit from this optimization?

I ask because we do this kind of deduplication inside of WithFields already as part of the foldLeft operation here. It will only keep the last valExpr for each name. So I think the optimized logical plan will be the same with or without this optimization in all scenarios? CMIIW

Copy link
Member Author

@viirya viirya Sep 22, 2020

Choose a reason for hiding this comment

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

You are right. It is eventually the same. But for some cases, before we extend WithFields, the expression tree might be very complex. This is coming from improving scalability of #29587. This is applied during I fixed the scalability issue. I found this is useful to reduce the complex of WithFields expression tree.

I will run these rules in #29587 to simplify expression tree before entering optimizer.

Copy link
Contributor

@fqaiser94 fqaiser94 Sep 23, 2020

Choose a reason for hiding this comment

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

Okay, so I took a look at the PR you linked and left a related comment there. I don't think you actually need this optimization for #29587

This optimization is only useful if someone uses WithFields to update the same field multiple times. However, it would simply be better to not update the same field multiple times. At the very least, we should not do this when we re-use this Expression internally within Spark.

Unfortunately, "bad" end-users might still update the same field multiple times. Assuming we should optimize for such users (not sure), since this batch is only applied half-way through the optimization cycle anyway, I think we could just move up the Batch("ReplaceWithFieldsExpression", Once, ReplaceWithFieldsExpression) to get the same benefit (which is just simplified tree). What do you reckon?

Copy link
Member Author

@viirya viirya Sep 23, 2020

Choose a reason for hiding this comment

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

Actually I'd like to run these rules to simplify WithFields tree early in analysis stage. During fixing scale issue of #29587, I thought that it is very likely to write bad WithFields tree. Once hitting that, it is very hard to debug and the analyzer/optimizer spend a lot of time traversing expression tree. So I think it is very useful keep this rule to simplify the expression tree, but I don't think we want to do ReplaceWithFieldsExpression in analysis stage.

Copy link
Contributor

Choose a reason for hiding this comment

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

ahh I see, yes, in the analysis stage this would likely be helpful!

Okay in that case, could this PR wait till #29795 goes in? I'm refactoring WithFields so this optimization would need to change anyway.

Copy link
Member Author

Choose a reason for hiding this comment

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

I'm fine to wait until #29795.


case WithFields(WithFields(struct, names1, valExprs1), names2, valExprs2) =>
WithFields(struct, names1 ++ names2, valExprs1 ++ valExprs2)
}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
* 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.{Alias, GetStructField, Literal, WithFields}
import org.apache.spark.sql.catalyst.plans.PlanTest
import org.apache.spark.sql.catalyst.plans.logical._
import org.apache.spark.sql.catalyst.rules._
import org.apache.spark.sql.internal.SQLConf

class OptimizeWithFieldsSuite extends PlanTest {

object Optimize extends RuleExecutor[LogicalPlan] {
val batches = Batch("OptimizeWithFields", FixedPoint(10),
OptimizeWithFields, SimplifyExtractValueOps) :: Nil
}

private val testRelation = LocalRelation('a.struct('a1.int))
private val testRelation2 = LocalRelation('a.struct('a1.int).notNull)

test("combines two WithFields") {
val originalQuery = testRelation
.select(Alias(
WithFields(
WithFields(
'a,
Seq("b1"),
Seq(Literal(4))),
Seq("c1"),
Seq(Literal(5))), "out")())

val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer = testRelation
.select(Alias(WithFields('a, Seq("b1", "c1"), Seq(Literal(4), Literal(5))), "out")())
.analyze

comparePlans(optimized, correctAnswer)
}

test("combines three WithFields") {
val originalQuery = testRelation
.select(Alias(
WithFields(
WithFields(
WithFields(
'a,
Seq("b1"),
Seq(Literal(4))),
Seq("c1"),
Seq(Literal(5))),
Seq("d1"),
Seq(Literal(6))), "out")())

val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer = testRelation
.select(Alias(WithFields('a, Seq("b1", "c1", "d1"), Seq(4, 5, 6).map(Literal(_))), "out")())
.analyze

comparePlans(optimized, correctAnswer)
}

test("SPARK-32941: optimize WithFields followed by GetStructField") {
val originalQuery = testRelation2
.select(Alias(
GetStructField(WithFields(
'a,
Seq("b1"),
Seq(Literal(4))), 1), "out")())

val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer = testRelation2
.select(Alias(Literal(4), "out")())
.analyze

comparePlans(optimized, correctAnswer)
}

test("SPARK-32941: optimize WithFields chain - case insensitive") {
val originalQuery = testRelation
.select(Alias(
WithFields(
WithFields(
'a,
Seq("b1"),
Seq(Literal(4))),
Seq("b1"),
Seq(Literal(5))), "out1")(),
Alias(
WithFields(
WithFields(
'a,
Seq("b1"),
Seq(Literal(4))),
Seq("B1"),
Seq(Literal(5))), "out2")())

val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer = testRelation
.select(
Alias(WithFields('a, Seq("b1"), Seq(Literal(5))), "out1")(),
Alias(WithFields('a, Seq("B1"), Seq(Literal(5))), "out2")())
.analyze

comparePlans(optimized, correctAnswer)
}

test("SPARK-32941: optimize WithFields chain - case sensitive") {
withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {
val originalQuery = testRelation
.select(Alias(
WithFields(
WithFields(
'a,
Seq("b1"),
Seq(Literal(4))),
Seq("b1"),
Seq(Literal(5))), "out1")(),
Alias(
WithFields(
WithFields(
'a,
Seq("b1"),
Seq(Literal(4))),
Seq("B1"),
Seq(Literal(5))), "out2")())

val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer = testRelation
.select(
Alias(WithFields('a, Seq("b1"), Seq(Literal(5))), "out1")(),
Alias(WithFields('a, Seq("b1", "B1"), Seq(Literal(4), Literal(5))), "out2")())
.analyze

comparePlans(optimized, correctAnswer)
}
}
}