Github user chenghao-intel commented on a diff in the pull request:
https://github.com/apache/spark/pull/8066#discussion_r37159219
--- Diff:
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
---
@@ -816,3 +818,92 @@ object RemoveLiteralFromGroupExpressions extends
Rule[LogicalPlan] {
a.copy(groupingExpressions = newGrouping)
}
}
+
+/**
+ * Remove the unnecessary evaluation from SortOrder, if they are already
in child's output.
+ *
+ * As an example, "select a + 1, b from t order by a + 1" will be analyzed
into:
+ * {{{
+ * Project(reference#2, b#0,
+ * Sort('a#1 + 1,
+ * Project(('a + 1).as("_c0")#2, b#0, a#1),
+ * Relation)
+ * }}}
+ * Then this rule can optimize it into:
+ * {{{
+ * Project(reference#2, b#0,
+ * Sort(reference#2,
+ * Project(('a + 1).as("_c0")#2, b#0, a#1),
+ * Relation)
+ * }}}
+ * Finally other optimize rules(column pruning, project collapse) can turn
it into:
+ * {{{
+ * Sort(reference#2,
+ * Project(('a + 1).as("_c0")#2, b#0),
+ * Relation)
+ * }}}
+ */
+object RemoveUnnecessarySortOrderEvaluation extends Rule[LogicalPlan] {
+ private def removeEvaluation(ordering: Seq[SortOrder], childOutput:
Seq[NamedExpression]) = {
+ ordering.map(order => {
+ val optimizedExpr = order.child.transformDown {
+ case expr =>
+ val index = childOutput.indexWhere {
+ case Alias(child, _) => child semanticEquals expr
+ case other => other semanticEquals expr
+ }
+ if (index == -1) {
+ expr
+ } else {
+ // Attribute is leaf expression so we can stop transforming
down.
+ childOutput(index).toAttribute
+ }
+ }
+ order.copy(child = optimizedExpr)
+ })
+ }
+
+ def apply(plan: LogicalPlan): LogicalPlan = plan transform {
+ case s @ Sort(ordering, _, Project(projectList, _)) =>
+ s.copy(order = removeEvaluation(ordering, projectList))
+
+ case s @ Sort(ordering, _, a @ Aggregate(_, aggs, _)) =>
+ // In `Analyzer` we will alias and add order-by expressions with
aggregation into underlying
+ // `Aggregate` and reference them in `Sort`, here we need to get
them back so that we can
+ // compare them with the aggregate expressions.
+ var originalAggs = aggs
+ val originalOrdering = ordering.map(order => order.child match {
+ case ref: AttributeReference =>
+ aggs.find(_.exprId == ref.exprId).collect {
+ case addedAgg @ Alias(aggExpr, "_aggOrdering") =>
--- End diff --
This's probably error-prone with the hard code in `Analyzer`, and actually
I just create a PR for the bug fixing at #8234
---
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]