cloud-fan commented on code in PR #47331:
URL: https://github.com/apache/spark/pull/47331#discussion_r1700332255
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InsertMapSortInGroupingExpressions.scala:
##########
@@ -34,12 +35,56 @@ object InsertMapSortInGroupingExpressions extends
Rule[LogicalPlan] {
_.containsPattern(AGGREGATE), ruleId) {
case a @ Aggregate(groupingExpr, _, _) =>
val newGrouping = groupingExpr.map { expr =>
- if (!expr.isInstanceOf[MapSort] &&
expr.dataType.isInstanceOf[MapType]) {
- MapSort(expr)
+ if (!expr.exists(_.isInstanceOf[MapSort])
+ && expr.dataType.existsRecursively(_.isInstanceOf[MapType])) {
+ insertMapSortRecursively(expr)
} else {
expr
}
}
a.copy(groupingExpressions = newGrouping)
}
+
+ /*
+ Inserts MapSort recursively taking into account when
+ it is nested inside a struct or array.
+ */
+ private def insertMapSortRecursively(e: Expression): Expression = {
+ e.dataType match {
+ case m: MapType =>
+ // Check if value type of MapType contains MapType (possibly nested)
+ // and special handle this case.
+ val mapSortExpr = if
(m.valueType.existsRecursively(_.isInstanceOf[MapType])) {
+ MapFromArrays(MapKeys(e), insertMapSortRecursively(MapValues(e)))
+ }
+ else {
+ e
+ }
+
+ MapSort(mapSortExpr)
+
+ case StructType(fields) =>
+ val struct = CreateNamedStruct(fields.zipWithIndex.flatMap { case (f,
i) =>
+ Seq(Literal(f.name), insertMapSortRecursively(
+ GetStructField(e, i, Some(f.name))))
+ }.toImmutableArraySeq)
+ if (struct.valExprs.forall(_.isInstanceOf[GetStructField])) {
+ // No field needs MapSort processing, just return the original
expression.
+ e
+ } else if (e.nullable) {
+ If(IsNull(e), Literal(null, struct.dataType), struct)
+ } else {
+ struct
+ }
+
+ case ArrayType(et, containsNull) =>
+ val param = NamedLambdaVariable("x", et, containsNull)
+ val funcBody = insertMapSortRecursively(param)
+
+ ArrayTransform(e, LambdaFunction(funcBody, Seq(param)))
Review Comment:
we should only do this if `et` contains MapType
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]