Github user marmbrus commented on a diff in the pull request:
https://github.com/apache/spark/pull/8066#discussion_r36696854
--- Diff:
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
---
@@ -813,3 +815,66 @@ 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)#2, b#0, a#1),
+ * Relation)
+ * }}}
+ * Then this rule can optimize it into:
+ * {{{
+ * Project(reference#2, b#0,
+ * Sort(reference#2,
+ * Project(('a + 1)#2, b#0, a#1),
+ * Relation)
+ * }}}
+ * Finally other optimize rules(column pruning, project collapse) can turn
it into:
+ * {{{
+ * Sort(reference#2,
+ * Project(('a + 1)#2, b#0),
+ * Relation)
+ * }}}
+ */
+object RemoveUnnecessarySortOrderEvaluation extends Rule[LogicalPlan] {
+ private def trimAliases(e: Expression) = e.transformUp {
+ case Alias(child, _) => child
+ }
+
+ private def removeEvaluation(ordering: Seq[SortOrder], exprs:
Seq[NamedExpression]) = {
+ val OrderingExprs = ordering.map(_.child).map(trimAliases)
+ val cleanedExprs = exprs.map(trimAliases)
+
+ ordering.zip(OrderingExprs).map { case (order, expr) =>
+ val index = cleanedExprs.indexWhere(_ semanticEquals expr)
+ if (index == -1) {
+ order
+ } else {
+ order.copy(child = exprs(index).toAttribute)
+ }
+ }
+ }
+
+ def apply(plan: LogicalPlan): LogicalPlan = plan transform {
+ case s @ Sort(ordering, _, Project(projectList, _)) =>
+ s.copy(order = removeEvaluation(ordering, projectList))
+
+ case s @ Sort(ordering, _, 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.
+ val originOrdering = ordering.map(order => order.child match {
--- End diff --
"original"
---
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]