-
Notifications
You must be signed in to change notification settings - Fork 29.3k
[SPARK-38533][SQL] DS V2 aggregate push-down supports project with alias #35823
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
13 commits
Select commit
Hold shift + click to select a range
97b7ee8
[SPARK-38533][SQL] DS V2 aggregate push-down supports project with alias
beliefer 6117481
Update code
beliefer 4dead89
Update code
beliefer a7c5504
Update code
beliefer 93e4fc4
Update code
beliefer 1a764d2
Update code
beliefer 9ebcd8e
Update code
beliefer 864d52d
Update code
beliefer 2be235c
Update code
beliefer 08a1b8e
Update code
beliefer 374e682
Update code
beliefer f0d0e70
Update code
beliefer 7a145e8
Update code
beliefer 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -19,21 +19,22 @@ package org.apache.spark.sql.execution.datasources.v2 | |
|
|
||
| import scala.collection.mutable | ||
|
|
||
| import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, AttributeReference, Cast, Divide, DivideDTInterval, DivideYMInterval, EqualTo, Expression, If, IntegerLiteral, Literal, NamedExpression, PredicateHelper, ProjectionOverSchema, SubqueryExpression} | ||
| import org.apache.spark.sql.catalyst.expressions.aggregate | ||
| import org.apache.spark.sql.catalyst.expressions.{aggregate, Alias, AliasHelper, And, Attribute, AttributeMap, AttributeReference, Cast, Divide, DivideDTInterval, DivideYMInterval, EqualTo, Expression, If, IntegerLiteral, Literal, NamedExpression, PredicateHelper, ProjectionOverSchema, SubqueryExpression} | ||
| import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression | ||
| import org.apache.spark.sql.catalyst.optimizer.CollapseProject.{buildCleanedProjectList, canCollapseExpressions} | ||
| import org.apache.spark.sql.catalyst.planning.ScanOperation | ||
| import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, Filter, LeafNode, Limit, LocalLimit, LogicalPlan, Project, Sample, Sort} | ||
| import org.apache.spark.sql.catalyst.rules.Rule | ||
| import org.apache.spark.sql.connector.expressions.SortOrder | ||
| import org.apache.spark.sql.connector.expressions.aggregate.{Aggregation, Avg, Count, GeneralAggregateFunc, Sum} | ||
| import org.apache.spark.sql.connector.read.{Scan, ScanBuilder, SupportsPushDownAggregates, SupportsPushDownFilters, V1Scan} | ||
| import org.apache.spark.sql.execution.datasources.DataSourceStrategy | ||
| import org.apache.spark.sql.internal.SQLConf | ||
| import org.apache.spark.sql.sources | ||
| import org.apache.spark.sql.types.{DataType, DayTimeIntervalType, LongType, StructType, YearMonthIntervalType} | ||
| import org.apache.spark.sql.util.SchemaUtils._ | ||
|
|
||
| object V2ScanRelationPushDown extends Rule[LogicalPlan] with PredicateHelper { | ||
| object V2ScanRelationPushDown extends Rule[LogicalPlan] with PredicateHelper with AliasHelper { | ||
| import DataSourceV2Implicits._ | ||
|
|
||
| def apply(plan: LogicalPlan): LogicalPlan = { | ||
|
|
@@ -88,27 +89,43 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] with PredicateHelper { | |
| filterCondition.map(Filter(_, sHolder)).getOrElse(sHolder) | ||
| } | ||
|
|
||
| def pushDownAggregates(plan: LogicalPlan): LogicalPlan = plan.transform { | ||
| private def collapseProject(plan: LogicalPlan): LogicalPlan = { | ||
| val alwaysInline = conf.getConf(SQLConf.COLLAPSE_PROJECT_ALWAYS_INLINE) | ||
| plan transformUp { | ||
| case agg @ Aggregate(_, aggregateExpressions, p: Project) | ||
| if canCollapseExpressions(aggregateExpressions, p.projectList, alwaysInline) => | ||
| agg.copy(aggregateExpressions = buildCleanedProjectList( | ||
| aggregateExpressions, p.projectList)) | ||
| } | ||
| } | ||
|
|
||
| def pushDownAggregates(plan: LogicalPlan): LogicalPlan = collapseProject(plan).transform { | ||
| // update the scan builder with agg pushdown and return a new plan with agg pushed | ||
| case aggNode @ Aggregate(groupingExpressions, resultExpressions, child) => | ||
| child match { | ||
| case ScanOperation(project, filters, sHolder: ScanBuilderHolder) | ||
| if filters.isEmpty && project.forall(_.isInstanceOf[AttributeReference]) => | ||
| if filters.isEmpty && project.forall(_.deterministic) => | ||
| sHolder.builder match { | ||
| case r: SupportsPushDownAggregates => | ||
| val aliasMap = getAliasMap(project) | ||
| val newResultExpressions = resultExpressions.map(replaceAliasWithAttr(_, aliasMap)) | ||
| val newGroupingExpressions = groupingExpressions.map { | ||
| case e: NamedExpression => replaceAliasWithAttr(e, aliasMap) | ||
| case other => other | ||
| } | ||
| val aggExprToOutputOrdinal = mutable.HashMap.empty[Expression, Int] | ||
| val aggregates = collectAggregates(resultExpressions, aggExprToOutputOrdinal) | ||
| val aggregates = collectAggregates(newResultExpressions, aggExprToOutputOrdinal) | ||
| val normalizedAggregates = DataSourceStrategy.normalizeExprs( | ||
| aggregates, sHolder.relation.output).asInstanceOf[Seq[AggregateExpression]] | ||
| val normalizedGroupingExpressions = DataSourceStrategy.normalizeExprs( | ||
| groupingExpressions, sHolder.relation.output) | ||
| newGroupingExpressions, sHolder.relation.output) | ||
| val translatedAggregates = DataSourceStrategy.translateAggregation( | ||
| normalizedAggregates, normalizedGroupingExpressions) | ||
| val (finalResultExpressions, finalAggregates, finalTranslatedAggregates) = { | ||
| val (selectedResultExpressions, selectedAggregates, selectedTranslatedAggregates) = { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why do we rename these?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's not confirmed yet. |
||
| if (translatedAggregates.isEmpty || | ||
| r.supportCompletePushDown(translatedAggregates.get) || | ||
| translatedAggregates.get.aggregateExpressions().forall(!_.isInstanceOf[Avg])) { | ||
| (resultExpressions, aggregates, translatedAggregates) | ||
| (newResultExpressions, aggregates, translatedAggregates) | ||
| } else { | ||
| // scalastyle:off | ||
| // The data source doesn't support the complete push-down of this aggregation. | ||
|
|
@@ -156,15 +173,15 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] with PredicateHelper { | |
| } | ||
| } | ||
|
|
||
| if (finalTranslatedAggregates.isEmpty) { | ||
| aggNode // return original plan node | ||
| } else if (!r.supportCompletePushDown(finalTranslatedAggregates.get) && | ||
| !supportPartialAggPushDown(finalTranslatedAggregates.get)) { | ||
| aggNode // return original plan node | ||
| if (selectedTranslatedAggregates.isEmpty) { | ||
| return plan // return original plan node | ||
| } else if (!r.supportCompletePushDown(selectedTranslatedAggregates.get) && | ||
| !supportPartialAggPushDown(selectedTranslatedAggregates.get)) { | ||
| return plan // return original plan node | ||
| } else { | ||
| val pushedAggregates = finalTranslatedAggregates.filter(r.pushAggregation) | ||
| val pushedAggregates = selectedTranslatedAggregates.filter(r.pushAggregation) | ||
| if (pushedAggregates.isEmpty) { | ||
| aggNode // return original plan node | ||
| return plan // return original plan node | ||
| } else { | ||
| // No need to do column pruning because only the aggregate columns are used as | ||
| // DataSourceV2ScanRelation output columns. All the other columns are not | ||
|
|
@@ -182,7 +199,7 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] with PredicateHelper { | |
| // +- RelationV2[c2#10, min(c1)#21, max(c1)#22] | ||
| // scalastyle:on | ||
| val newOutput = scan.readSchema().toAttributes | ||
| assert(newOutput.length == groupingExpressions.length + finalAggregates.length) | ||
| assert(newOutput.length == groupingExpressions.length + selectedAggregates.length) | ||
| val groupAttrs = normalizedGroupingExpressions.zip(newOutput).map { | ||
| case (a: Attribute, b: Attribute) => b.withExprId(a.exprId) | ||
| case (_, b) => b | ||
|
|
@@ -203,8 +220,14 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] with PredicateHelper { | |
| val wrappedScan = getWrappedScan(scan, sHolder, pushedAggregates) | ||
| val scanRelation = | ||
| DataSourceV2ScanRelation(sHolder.relation, wrappedScan, output) | ||
| val aliasAttrMap = getAttrToAliasMap(aliasMap) | ||
| val finalResultExpressions = selectedResultExpressions.map { | ||
| case attr: AttributeReference => | ||
| aliasAttrMap.getOrElse(attr, attr) | ||
| case other => other | ||
| } | ||
| if (r.supportCompletePushDown(pushedAggregates.get)) { | ||
| val projectExpressions = resultExpressions.map { expr => | ||
| val projectExpressions = finalResultExpressions.map { expr => | ||
| // TODO At present, only push down group by attribute is supported. | ||
| // In future, more attribute conversion is extended here. e.g. GetStructField | ||
| expr.transform { | ||
|
|
@@ -259,12 +282,31 @@ object V2ScanRelationPushDown extends Rule[LogicalPlan] with PredicateHelper { | |
| } | ||
| } | ||
| } | ||
| case _ => aggNode | ||
| case _ => return plan | ||
| } | ||
| case _ => aggNode | ||
| case _ => return plan | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Replace all alias, with the aliased attribute. | ||
| */ | ||
| private def replaceAliasWithAttr( | ||
| expr: NamedExpression, | ||
| aliasMap: AttributeMap[Alias]): NamedExpression = { | ||
| replaceAliasButKeepName(expr, aliasMap).transform { | ||
| case Alias(attr: Attribute, _) => attr | ||
| }.asInstanceOf[NamedExpression] | ||
| } | ||
|
|
||
| protected def getAttrToAliasMap(aliasMap: AttributeMap[Alias]): AttributeMap[Alias] = { | ||
| val attrToAliasMap = aliasMap.values.toSeq.collect { | ||
| case alias @ Alias(originAttr: Attribute, _) => | ||
| (originAttr, alias) | ||
| } | ||
| AttributeMap(attrToAliasMap) | ||
| } | ||
|
|
||
| private def collectAggregates(resultExpressions: Seq[NamedExpression], | ||
| aggExprToOutputOrdinal: mutable.HashMap[Expression, Int]): Seq[AggregateExpression] = { | ||
| var ordinal = 0 | ||
|
|
||
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.
can we make the code more explicit? We need to clearly show the steps
AliasHelperas this is not a common logic)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.
Thank you for the good idea.