-
Notifications
You must be signed in to change notification settings - Fork 28.9k
[DRAFT][SQL] Hash aggregate support for strings with collation #45929
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
c91f441
Draft commit
uros-db 76728ac
Preserve idempotence
uros-db b4733c3
Fix agg expressions
uros-db 830f63d
Fix tests
uros-db c0f9396
scalastyle fix
uros-db dc683d7
Remove unused imports
uros-db c8855a5
Support array<string> (in progress)
uros-db a7f7960
Merge branch 'master' into SPARK-47690
uros-db 05c0378
Fix rewrite for array<string>
uros-db ec447e3
GROUP BY / DISTINCT tests
uros-db File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
148 changes: 148 additions & 0 deletions
148
...alyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteGroupByCollation.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| /* | ||
| * 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.analysis | ||
|
|
||
| import java.util.Locale | ||
|
|
||
| import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference, ExpectsInputTypes, Expression, UnaryExpression} | ||
| import org.apache.spark.sql.catalyst.expressions.aggregate.First | ||
| import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext, ExprCode} | ||
| import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LogicalPlan} | ||
| import org.apache.spark.sql.catalyst.rules.Rule | ||
| import org.apache.spark.sql.catalyst.util.{CollationFactory, GenericArrayData} | ||
| import org.apache.spark.sql.internal.types.{AbstractArrayType, StringTypeAnyCollation} | ||
| import org.apache.spark.sql.types.{AbstractDataType, ArrayType, DataType, StringType, TypeCollection} | ||
| import org.apache.spark.unsafe.types.UTF8String | ||
|
|
||
| /** | ||
| * A rule that rewrites aggregation operations using plans that operate on collated strings. | ||
| */ | ||
| object RewriteGroupByCollation extends Rule[LogicalPlan] { | ||
| def apply(plan: LogicalPlan): LogicalPlan = plan transformUpWithNewOutput { | ||
| case a: Aggregate => | ||
| val aliasMap = a.groupingExpressions.collect { | ||
| case attr: AttributeReference if attr.dataType.isInstanceOf[StringType] => | ||
| attr -> CollationKey(attr) | ||
| case attr: AttributeReference if attr.dataType.isInstanceOf[ArrayType] | ||
| && attr.dataType.asInstanceOf[ArrayType].elementType.isInstanceOf[StringType] => | ||
| attr -> CollationKey(attr) | ||
| }.toMap | ||
|
|
||
| val newGroupingExpressions = a.groupingExpressions.map { | ||
| case attr: AttributeReference if aliasMap.contains(attr) => | ||
| aliasMap(attr) | ||
| case other => other | ||
| } | ||
|
|
||
| val newAggregateExpressions = a.aggregateExpressions.map { | ||
| case attr: AttributeReference if aliasMap.contains(attr) => | ||
| Alias(First(attr, ignoreNulls = false).toAggregateExpression(), attr.name)() | ||
| case other => other | ||
| } | ||
|
|
||
| val newAggregate = a.copy( | ||
| groupingExpressions = newGroupingExpressions, | ||
| aggregateExpressions = newAggregateExpressions | ||
| ) | ||
|
|
||
| (newAggregate, a.output.zip(newAggregate.output)) | ||
| } | ||
| } | ||
|
|
||
| case class CollationKey(expr: Expression) extends UnaryExpression with ExpectsInputTypes { | ||
| override def inputTypes: Seq[AbstractDataType] = | ||
| Seq(TypeCollection(StringTypeAnyCollation, AbstractArrayType(StringTypeAnyCollation))) | ||
| override def dataType: DataType = expr.dataType | ||
|
|
||
| final lazy val collationId: Int = dataType match { | ||
| case _: StringType => | ||
| dataType.asInstanceOf[StringType].collationId | ||
| case ArrayType(_: StringType, _) => | ||
| val arr = dataType.asInstanceOf[ArrayType] | ||
| arr.elementType.asInstanceOf[StringType].collationId | ||
| } | ||
|
|
||
| override def nullSafeEval(input: Any): Any = dataType match { | ||
| case _: StringType => | ||
| getCollationKey(input.asInstanceOf[UTF8String]) | ||
| case ArrayType(_: StringType, _) => | ||
| input match { | ||
| case arr: Array[UTF8String] => | ||
| arr.map(getCollationKey) | ||
| case arr: GenericArrayData => | ||
| val result = new Array[UTF8String](arr.numElements()) | ||
| for (i <- 0 until arr.numElements()) { | ||
| result(i) = getCollationKey(arr.getUTF8String(i)) | ||
| } | ||
| new GenericArrayData(result) | ||
| case _ => | ||
| None | ||
| } | ||
| } | ||
|
|
||
| def getCollationKey(str: UTF8String): UTF8String = { | ||
| if (collationId == CollationFactory.UTF8_BINARY_COLLATION_ID) { | ||
| str | ||
| } else if (collationId == CollationFactory.UTF8_BINARY_LCASE_COLLATION_ID) { | ||
| UTF8String.fromString(str.toString.toLowerCase(Locale.ROOT)) | ||
| } else { | ||
| val collator = CollationFactory.fetchCollation(collationId).collator | ||
| val collationKey = collator.getCollationKey(str.toString) | ||
| UTF8String.fromBytes(collationKey.toByteArray) | ||
| } | ||
| } | ||
|
|
||
| override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = dataType match { | ||
| case _: StringType => | ||
| if (collationId == CollationFactory.UTF8_BINARY_COLLATION_ID) { | ||
| defineCodeGen(ctx, ev, c => s"$c") | ||
| } else if (collationId == CollationFactory.UTF8_BINARY_LCASE_COLLATION_ID) { | ||
| defineCodeGen(ctx, ev, c => s"$c.toLowerCase()") | ||
| } else { | ||
| defineCodeGen(ctx, ev, c => s"UTF8String.fromBytes(CollationFactory.fetchCollation" + | ||
| s"($collationId).collator.getCollationKey($c.toString()).toByteArray())") | ||
| } | ||
| case ArrayType(_: StringType, _) => | ||
| val expr = ctx.addReferenceObj("this", this) | ||
| val arrData = ctx.freshName("arrData") | ||
| val arrLength = ctx.freshName("arrLength") | ||
| val arrResult = ctx.freshName("arrResult") | ||
| val arrIndex = ctx.freshName("arrIndex") | ||
| nullSafeCodeGen(ctx, ev, eval => { | ||
| s""" | ||
| |if ($eval instanceof ArrayData) { | ||
| | ArrayData $arrData = (ArrayData)$eval; | ||
| | int $arrLength = $arrData.numElements(); | ||
| | UTF8String[] $arrResult = new UTF8String[$arrLength]; | ||
| | for (int $arrIndex = 0; $arrIndex < $arrLength; $arrIndex++) { | ||
| | $arrResult[$arrIndex] = $expr.getCollationKey($arrData.getUTF8String($arrIndex)); | ||
| | } | ||
| | ${ev.value} = new GenericArrayData($arrResult); | ||
| |} else { | ||
| | ${ev.value} = null; | ||
| |} | ||
| """.stripMargin | ||
| }) | ||
| } | ||
|
|
||
| override protected def withNewChildInternal(newChild: Expression): Expression = { | ||
| copy(expr = newChild) | ||
| } | ||
|
|
||
| override def child: Expression = expr | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why do we need this change?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
without it, it hits the
QueryCompilationErrors.columnNotInGroupByClauseError(e)with error: Job aborted due to stage failure: Task 0 in stage 2.0 failed 1 times, most recent failure: Lost task 0.0 in stage 2.0 (TID 2) (192.168.15.30 executor driver): org.apache.spark.SparkException: [INTERNAL_ERROR] Couldn't find name#17 in [collationkey(name#17)#30,count(1)#19L] SQLSTATE: XX000
with query plan:
so name#17 is not found in groupingExpressions