morrySnow commented on code in PR #31811: URL: https://github.com/apache/doris/pull/31811#discussion_r1515925604
########## fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/MergeAggregate.java: ########## @@ -0,0 +1,195 @@ +// 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.doris.nereids.rules.rewrite; + +import org.apache.doris.nereids.rules.Rule; +import org.apache.doris.nereids.rules.RuleType; +import org.apache.doris.nereids.trees.expressions.Alias; +import org.apache.doris.nereids.trees.expressions.ExprId; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.expressions.NamedExpression; +import org.apache.doris.nereids.trees.expressions.Slot; +import org.apache.doris.nereids.trees.expressions.SlotReference; +import org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction; +import org.apache.doris.nereids.trees.plans.Plan; +import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate; +import org.apache.doris.nereids.trees.plans.logical.LogicalProject; +import org.apache.doris.nereids.util.ExpressionUtils; +import org.apache.doris.nereids.util.PlanUtils; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * MergeAggregate + */ +public class MergeAggregate implements RewriteRuleFactory { + private static final ImmutableSet<String> ALLOW_MERGE_AGGREGATE_FUNCTIONS = + ImmutableSet.of("min", "max", "sum", "any_value"); + + private Plan mergeTwoAggregate(Plan plan) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalAggregate<Plan> innerAgg = (LogicalAggregate<Plan>) outerAgg.child(); + + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc = innerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .collect(Collectors.toMap(NamedExpression::getExprId, value -> (AggregateFunction) value.child(0))); Review Comment: nit: add mergeFunction in case of duplicate key ########## fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/MergeAggregate.java: ########## @@ -0,0 +1,195 @@ +// 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.doris.nereids.rules.rewrite; + +import org.apache.doris.nereids.rules.Rule; +import org.apache.doris.nereids.rules.RuleType; +import org.apache.doris.nereids.trees.expressions.Alias; +import org.apache.doris.nereids.trees.expressions.ExprId; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.expressions.NamedExpression; +import org.apache.doris.nereids.trees.expressions.Slot; +import org.apache.doris.nereids.trees.expressions.SlotReference; +import org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction; +import org.apache.doris.nereids.trees.plans.Plan; +import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate; +import org.apache.doris.nereids.trees.plans.logical.LogicalProject; +import org.apache.doris.nereids.util.ExpressionUtils; +import org.apache.doris.nereids.util.PlanUtils; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * MergeAggregate + */ +public class MergeAggregate implements RewriteRuleFactory { + private static final ImmutableSet<String> ALLOW_MERGE_AGGREGATE_FUNCTIONS = + ImmutableSet.of("min", "max", "sum", "any_value"); + + private Plan mergeTwoAggregate(Plan plan) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalAggregate<Plan> innerAgg = (LogicalAggregate<Plan>) outerAgg.child(); + + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc = innerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .collect(Collectors.toMap(NamedExpression::getExprId, value -> (AggregateFunction) value.child(0))); + + List<NamedExpression> newOutputExpressions = outerAgg.getOutputExpressions().stream() + .map(e -> rewriteAggregateFunction(e, innerAggExprIdToAggFunc)) + .collect(Collectors.toList()); + return outerAgg.withAggOutput(newOutputExpressions).withChildren(innerAgg.children()); + } + + private Plan mergeAggProjectAgg(Plan plan) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalProject<Plan> project = (LogicalProject<Plan>) outerAgg.child(); + LogicalAggregate<Plan> innerAgg = (LogicalAggregate<Plan>) project.child(); + + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc = innerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .collect(Collectors.toMap(NamedExpression::getExprId, value -> (AggregateFunction) value.child(0))); + // rewrite agg function. e.g. max(max) + List<NamedExpression> newAggFunc = outerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .map(e -> rewriteAggregateFunction(e, innerAggExprIdToAggFunc)) + .collect(Collectors.toList()); + // rewrite agg function directly refer to the slot below the project + Map<Slot, Expression> replaceMap = ExpressionUtils.generateReplaceMap(project.getProjects()); + newAggFunc = newAggFunc.stream() + .map(expr -> (NamedExpression) ExpressionUtils.replaceExpression(expr, replaceMap)) + .collect(Collectors.toList()); + + // replace groupByKeys directly refer to the slot below the project + List<Expression> newGroupBy = PlanUtils.replaceExpressionByProjections(project.getProjects(), + outerAgg.getGroupByExpressions()); + List<NamedExpression> newOutputExpressions = ImmutableList.<NamedExpression>builder() + .addAll(newGroupBy.stream().map(slot -> (NamedExpression) slot).iterator()) + .addAll(newAggFunc).build(); + // construct agg + LogicalAggregate<Plan> resAgg = outerAgg.withGroupByAndOutput(newGroupBy, newOutputExpressions) + .withChildren(innerAgg.children()); + + // construct upper project + Map<SlotReference, Alias> childToAlias = project.getProjects().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof SlotReference)) + .collect(Collectors.toMap(alias -> (SlotReference) alias.child(0), alias -> (Alias) alias)); + List<Expression> newProjectGroupBy = ExpressionUtils.replace(newGroupBy, childToAlias); + List<NamedExpression> upperProjects = ImmutableList.<NamedExpression>builder() + .addAll(newProjectGroupBy.stream().map(slot -> (NamedExpression) slot).iterator()) + .addAll(newAggFunc.stream().map(expr -> (NamedExpression) expr.toSlot()).iterator()) + .build(); + return new LogicalProject<Plan>(upperProjects, resAgg); + } + + private NamedExpression rewriteAggregateFunction(NamedExpression e, + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc) { + return (NamedExpression) e.rewriteDownShortCircuit(expr -> { + if (expr instanceof Alias && ((Alias) expr).child() instanceof AggregateFunction) { + Alias alias = (Alias) expr; + AggregateFunction aggFunc = (AggregateFunction) alias.child(); + ExprId childExprId = ((SlotReference) aggFunc.child(0)).getExprId(); + if (innerAggExprIdToAggFunc.containsKey(childExprId)) { + return new Alias(alias.getExprId(), innerAggExprIdToAggFunc.get(childExprId), + alias.getName()); + } else { + return expr; + } + } else { + return expr; + } + }); + } + + private boolean canMergeAggregate(Plan plan, boolean hasProject) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalAggregate<Plan> innerAgg = hasProject ? (LogicalAggregate<Plan>) outerAgg.child().child(0) + : (LogicalAggregate<Plan>) outerAgg.child(); + + List<Expression> outerAggGroupByKeys = outerAgg.getGroupByExpressions(); + if (hasProject) { + LogicalProject<Plan> project = (LogicalProject<Plan>) outerAgg.child(); + outerAggGroupByKeys = PlanUtils.replaceExpressionByProjections(project.getProjects(), outerAggGroupByKeys); + } + + if (!new HashSet<>(innerAgg.getGroupByExpressions()).containsAll(outerAggGroupByKeys)) { + return false; + } + + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc = innerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .collect(Collectors.toMap(NamedExpression::getExprId, value -> (AggregateFunction) value.child(0))); + Set<AggregateFunction> aggregateFunctions = outerAgg.getAggregateFunctions(); + for (AggregateFunction outerFunc : aggregateFunctions) { + if (!(ALLOW_MERGE_AGGREGATE_FUNCTIONS.contains(outerFunc.getName()))) { + return false; + } + if (outerFunc.isDistinct()) { + return false; + } + // not support outerAggFunc: sum(a+1),sum(a+b) + if (!(outerFunc.child(0) instanceof SlotReference)) { + return false; + } + ExprId childExprId = ((SlotReference) outerFunc.child(0)).getExprId(); + if (innerAggExprIdToAggFunc.containsKey(childExprId)) { + AggregateFunction innerFunc = innerAggExprIdToAggFunc.get(childExprId); + if (innerFunc.isDistinct()) { + return false; + } Review Comment: inner distinct is ok if outer group by keys are exactly same with inner keys? ########## fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/MergeAggregate.java: ########## @@ -0,0 +1,195 @@ +// 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.doris.nereids.rules.rewrite; + +import org.apache.doris.nereids.rules.Rule; +import org.apache.doris.nereids.rules.RuleType; +import org.apache.doris.nereids.trees.expressions.Alias; +import org.apache.doris.nereids.trees.expressions.ExprId; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.expressions.NamedExpression; +import org.apache.doris.nereids.trees.expressions.Slot; +import org.apache.doris.nereids.trees.expressions.SlotReference; +import org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction; +import org.apache.doris.nereids.trees.plans.Plan; +import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate; +import org.apache.doris.nereids.trees.plans.logical.LogicalProject; +import org.apache.doris.nereids.util.ExpressionUtils; +import org.apache.doris.nereids.util.PlanUtils; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * MergeAggregate + */ +public class MergeAggregate implements RewriteRuleFactory { + private static final ImmutableSet<String> ALLOW_MERGE_AGGREGATE_FUNCTIONS = + ImmutableSet.of("min", "max", "sum", "any_value"); + + private Plan mergeTwoAggregate(Plan plan) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalAggregate<Plan> innerAgg = (LogicalAggregate<Plan>) outerAgg.child(); + Review Comment: ```suggestion private Plan mergeTwoAggregate(LogicalAggregate<LogicalAggregate<Plan>> outerAgg) { LogicalAggregate<Plan> innerAgg = outerAgg.child(); ``` ########## fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/MergeAggregate.java: ########## @@ -0,0 +1,195 @@ +// 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.doris.nereids.rules.rewrite; + +import org.apache.doris.nereids.rules.Rule; +import org.apache.doris.nereids.rules.RuleType; +import org.apache.doris.nereids.trees.expressions.Alias; +import org.apache.doris.nereids.trees.expressions.ExprId; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.expressions.NamedExpression; +import org.apache.doris.nereids.trees.expressions.Slot; +import org.apache.doris.nereids.trees.expressions.SlotReference; +import org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction; +import org.apache.doris.nereids.trees.plans.Plan; +import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate; +import org.apache.doris.nereids.trees.plans.logical.LogicalProject; +import org.apache.doris.nereids.util.ExpressionUtils; +import org.apache.doris.nereids.util.PlanUtils; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * MergeAggregate + */ +public class MergeAggregate implements RewriteRuleFactory { + private static final ImmutableSet<String> ALLOW_MERGE_AGGREGATE_FUNCTIONS = + ImmutableSet.of("min", "max", "sum", "any_value"); + + private Plan mergeTwoAggregate(Plan plan) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalAggregate<Plan> innerAgg = (LogicalAggregate<Plan>) outerAgg.child(); + + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc = innerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .collect(Collectors.toMap(NamedExpression::getExprId, value -> (AggregateFunction) value.child(0))); + + List<NamedExpression> newOutputExpressions = outerAgg.getOutputExpressions().stream() + .map(e -> rewriteAggregateFunction(e, innerAggExprIdToAggFunc)) + .collect(Collectors.toList()); + return outerAgg.withAggOutput(newOutputExpressions).withChildren(innerAgg.children()); + } + + private Plan mergeAggProjectAgg(Plan plan) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalProject<Plan> project = (LogicalProject<Plan>) outerAgg.child(); + LogicalAggregate<Plan> innerAgg = (LogicalAggregate<Plan>) project.child(); + + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc = innerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .collect(Collectors.toMap(NamedExpression::getExprId, value -> (AggregateFunction) value.child(0))); + // rewrite agg function. e.g. max(max) + List<NamedExpression> newAggFunc = outerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .map(e -> rewriteAggregateFunction(e, innerAggExprIdToAggFunc)) + .collect(Collectors.toList()); + // rewrite agg function directly refer to the slot below the project + Map<Slot, Expression> replaceMap = ExpressionUtils.generateReplaceMap(project.getProjects()); + newAggFunc = newAggFunc.stream() + .map(expr -> (NamedExpression) ExpressionUtils.replaceExpression(expr, replaceMap)) + .collect(Collectors.toList()); + + // replace groupByKeys directly refer to the slot below the project + List<Expression> newGroupBy = PlanUtils.replaceExpressionByProjections(project.getProjects(), + outerAgg.getGroupByExpressions()); + List<NamedExpression> newOutputExpressions = ImmutableList.<NamedExpression>builder() + .addAll(newGroupBy.stream().map(slot -> (NamedExpression) slot).iterator()) + .addAll(newAggFunc).build(); + // construct agg + LogicalAggregate<Plan> resAgg = outerAgg.withGroupByAndOutput(newGroupBy, newOutputExpressions) + .withChildren(innerAgg.children()); + + // construct upper project + Map<SlotReference, Alias> childToAlias = project.getProjects().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof SlotReference)) + .collect(Collectors.toMap(alias -> (SlotReference) alias.child(0), alias -> (Alias) alias)); + List<Expression> newProjectGroupBy = ExpressionUtils.replace(newGroupBy, childToAlias); + List<NamedExpression> upperProjects = ImmutableList.<NamedExpression>builder() + .addAll(newProjectGroupBy.stream().map(slot -> (NamedExpression) slot).iterator()) + .addAll(newAggFunc.stream().map(expr -> (NamedExpression) expr.toSlot()).iterator()) + .build(); + return new LogicalProject<Plan>(upperProjects, resAgg); + } + + private NamedExpression rewriteAggregateFunction(NamedExpression e, + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc) { + return (NamedExpression) e.rewriteDownShortCircuit(expr -> { + if (expr instanceof Alias && ((Alias) expr).child() instanceof AggregateFunction) { + Alias alias = (Alias) expr; + AggregateFunction aggFunc = (AggregateFunction) alias.child(); + ExprId childExprId = ((SlotReference) aggFunc.child(0)).getExprId(); + if (innerAggExprIdToAggFunc.containsKey(childExprId)) { + return new Alias(alias.getExprId(), innerAggExprIdToAggFunc.get(childExprId), + alias.getName()); + } else { + return expr; + } + } else { + return expr; + } + }); + } + + private boolean canMergeAggregate(Plan plan, boolean hasProject) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalAggregate<Plan> innerAgg = hasProject ? (LogicalAggregate<Plan>) outerAgg.child().child(0) + : (LogicalAggregate<Plan>) outerAgg.child(); + + List<Expression> outerAggGroupByKeys = outerAgg.getGroupByExpressions(); + if (hasProject) { + LogicalProject<Plan> project = (LogicalProject<Plan>) outerAgg.child(); + outerAggGroupByKeys = PlanUtils.replaceExpressionByProjections(project.getProjects(), outerAggGroupByKeys); + } + + if (!new HashSet<>(innerAgg.getGroupByExpressions()).containsAll(outerAggGroupByKeys)) { + return false; + } + + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc = innerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .collect(Collectors.toMap(NamedExpression::getExprId, value -> (AggregateFunction) value.child(0))); + Set<AggregateFunction> aggregateFunctions = outerAgg.getAggregateFunctions(); + for (AggregateFunction outerFunc : aggregateFunctions) { + if (!(ALLOW_MERGE_AGGREGATE_FUNCTIONS.contains(outerFunc.getName()))) { + return false; + } + if (outerFunc.isDistinct()) { + return false; + } + // not support outerAggFunc: sum(a+1),sum(a+b) + if (!(outerFunc.child(0) instanceof SlotReference)) { + return false; + } + ExprId childExprId = ((SlotReference) outerFunc.child(0)).getExprId(); + if (innerAggExprIdToAggFunc.containsKey(childExprId)) { + AggregateFunction innerFunc = innerAggExprIdToAggFunc.get(childExprId); + if (innerFunc.isDistinct()) { + return false; + } + // support sum(sum),min(min),max(max),sum(count),any_value(any_value) + if (!(outerFunc.getName().equals("sum") && innerFunc.getName().equals("count")) Review Comment: trans `sum(count())` to `count()` lead to nullable changed if outer agg is scalar agg. so we need to wrap the final expression with `nullable()` function to change its nullable to true ########## regression-test/suites/nereids_rules_p0/merge_aggregate/merge_aggregate.groovy: ########## @@ -0,0 +1,136 @@ +// 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. +suite("merge_aggregate") { + sql "SET enable_nereids_planner=true" + sql "SET enable_fallback_to_original_planner=false" + sql """ + DROP TABLE IF EXISTS mal_test1 + """ + + sql """ + create table mal_test1(pk int, a int, b int) distributed by hash(pk) buckets 10 + properties('replication_num' = '1'); + """ + + sql """ + insert into mal_test1 values(2,1,3),(1,1,2),(3,5,6),(6,null,6),(4,5,6); + """ + + sql "sync" + + qt_maxMax_minMin_sumSum_sumCount """ Review Comment: add some shape check or ut to ensure merge agg work well ########## fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/MergeAggregate.java: ########## @@ -0,0 +1,195 @@ +// 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.doris.nereids.rules.rewrite; + +import org.apache.doris.nereids.rules.Rule; +import org.apache.doris.nereids.rules.RuleType; +import org.apache.doris.nereids.trees.expressions.Alias; +import org.apache.doris.nereids.trees.expressions.ExprId; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.expressions.NamedExpression; +import org.apache.doris.nereids.trees.expressions.Slot; +import org.apache.doris.nereids.trees.expressions.SlotReference; +import org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction; +import org.apache.doris.nereids.trees.plans.Plan; +import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate; +import org.apache.doris.nereids.trees.plans.logical.LogicalProject; +import org.apache.doris.nereids.util.ExpressionUtils; +import org.apache.doris.nereids.util.PlanUtils; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * MergeAggregate + */ +public class MergeAggregate implements RewriteRuleFactory { + private static final ImmutableSet<String> ALLOW_MERGE_AGGREGATE_FUNCTIONS = + ImmutableSet.of("min", "max", "sum", "any_value"); + + private Plan mergeTwoAggregate(Plan plan) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalAggregate<Plan> innerAgg = (LogicalAggregate<Plan>) outerAgg.child(); + + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc = innerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .collect(Collectors.toMap(NamedExpression::getExprId, value -> (AggregateFunction) value.child(0))); + + List<NamedExpression> newOutputExpressions = outerAgg.getOutputExpressions().stream() + .map(e -> rewriteAggregateFunction(e, innerAggExprIdToAggFunc)) + .collect(Collectors.toList()); + return outerAgg.withAggOutput(newOutputExpressions).withChildren(innerAgg.children()); + } + + private Plan mergeAggProjectAgg(Plan plan) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalProject<Plan> project = (LogicalProject<Plan>) outerAgg.child(); + LogicalAggregate<Plan> innerAgg = (LogicalAggregate<Plan>) project.child(); Review Comment: private Plan mergeAggProjectAgg(LogicalAggregate<LogicalProject<LogicalAggregate<Plan>>> outerAgg) { LogicalProject<LogicalAggregate<Plan>> project = outerAgg.child(); LogicalAggregate<Plan> innerAgg = project.child(); ########## fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/MergeAggregate.java: ########## @@ -0,0 +1,195 @@ +// 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.doris.nereids.rules.rewrite; + +import org.apache.doris.nereids.rules.Rule; +import org.apache.doris.nereids.rules.RuleType; +import org.apache.doris.nereids.trees.expressions.Alias; +import org.apache.doris.nereids.trees.expressions.ExprId; +import org.apache.doris.nereids.trees.expressions.Expression; +import org.apache.doris.nereids.trees.expressions.NamedExpression; +import org.apache.doris.nereids.trees.expressions.Slot; +import org.apache.doris.nereids.trees.expressions.SlotReference; +import org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction; +import org.apache.doris.nereids.trees.plans.Plan; +import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate; +import org.apache.doris.nereids.trees.plans.logical.LogicalProject; +import org.apache.doris.nereids.util.ExpressionUtils; +import org.apache.doris.nereids.util.PlanUtils; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * MergeAggregate + */ +public class MergeAggregate implements RewriteRuleFactory { + private static final ImmutableSet<String> ALLOW_MERGE_AGGREGATE_FUNCTIONS = + ImmutableSet.of("min", "max", "sum", "any_value"); + + private Plan mergeTwoAggregate(Plan plan) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalAggregate<Plan> innerAgg = (LogicalAggregate<Plan>) outerAgg.child(); + + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc = innerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .collect(Collectors.toMap(NamedExpression::getExprId, value -> (AggregateFunction) value.child(0))); + + List<NamedExpression> newOutputExpressions = outerAgg.getOutputExpressions().stream() + .map(e -> rewriteAggregateFunction(e, innerAggExprIdToAggFunc)) + .collect(Collectors.toList()); + return outerAgg.withAggOutput(newOutputExpressions).withChildren(innerAgg.children()); + } + + private Plan mergeAggProjectAgg(Plan plan) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalProject<Plan> project = (LogicalProject<Plan>) outerAgg.child(); + LogicalAggregate<Plan> innerAgg = (LogicalAggregate<Plan>) project.child(); + + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc = innerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .collect(Collectors.toMap(NamedExpression::getExprId, value -> (AggregateFunction) value.child(0))); + // rewrite agg function. e.g. max(max) + List<NamedExpression> newAggFunc = outerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .map(e -> rewriteAggregateFunction(e, innerAggExprIdToAggFunc)) + .collect(Collectors.toList()); + // rewrite agg function directly refer to the slot below the project + Map<Slot, Expression> replaceMap = ExpressionUtils.generateReplaceMap(project.getProjects()); + newAggFunc = newAggFunc.stream() + .map(expr -> (NamedExpression) ExpressionUtils.replaceExpression(expr, replaceMap)) + .collect(Collectors.toList()); + + // replace groupByKeys directly refer to the slot below the project + List<Expression> newGroupBy = PlanUtils.replaceExpressionByProjections(project.getProjects(), + outerAgg.getGroupByExpressions()); + List<NamedExpression> newOutputExpressions = ImmutableList.<NamedExpression>builder() + .addAll(newGroupBy.stream().map(slot -> (NamedExpression) slot).iterator()) + .addAll(newAggFunc).build(); + // construct agg + LogicalAggregate<Plan> resAgg = outerAgg.withGroupByAndOutput(newGroupBy, newOutputExpressions) + .withChildren(innerAgg.children()); + + // construct upper project + Map<SlotReference, Alias> childToAlias = project.getProjects().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof SlotReference)) + .collect(Collectors.toMap(alias -> (SlotReference) alias.child(0), alias -> (Alias) alias)); + List<Expression> newProjectGroupBy = ExpressionUtils.replace(newGroupBy, childToAlias); + List<NamedExpression> upperProjects = ImmutableList.<NamedExpression>builder() + .addAll(newProjectGroupBy.stream().map(slot -> (NamedExpression) slot).iterator()) + .addAll(newAggFunc.stream().map(expr -> (NamedExpression) expr.toSlot()).iterator()) + .build(); + return new LogicalProject<Plan>(upperProjects, resAgg); + } + + private NamedExpression rewriteAggregateFunction(NamedExpression e, + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc) { + return (NamedExpression) e.rewriteDownShortCircuit(expr -> { + if (expr instanceof Alias && ((Alias) expr).child() instanceof AggregateFunction) { + Alias alias = (Alias) expr; + AggregateFunction aggFunc = (AggregateFunction) alias.child(); + ExprId childExprId = ((SlotReference) aggFunc.child(0)).getExprId(); + if (innerAggExprIdToAggFunc.containsKey(childExprId)) { + return new Alias(alias.getExprId(), innerAggExprIdToAggFunc.get(childExprId), + alias.getName()); + } else { + return expr; + } + } else { + return expr; + } + }); + } + + private boolean canMergeAggregate(Plan plan, boolean hasProject) { + LogicalAggregate<Plan> outerAgg = (LogicalAggregate<Plan>) plan; + LogicalAggregate<Plan> innerAgg = hasProject ? (LogicalAggregate<Plan>) outerAgg.child().child(0) + : (LogicalAggregate<Plan>) outerAgg.child(); + + List<Expression> outerAggGroupByKeys = outerAgg.getGroupByExpressions(); + if (hasProject) { + LogicalProject<Plan> project = (LogicalProject<Plan>) outerAgg.child(); + outerAggGroupByKeys = PlanUtils.replaceExpressionByProjections(project.getProjects(), outerAggGroupByKeys); + } + + if (!new HashSet<>(innerAgg.getGroupByExpressions()).containsAll(outerAggGroupByKeys)) { + return false; + } + + Map<ExprId, AggregateFunction> innerAggExprIdToAggFunc = innerAgg.getOutputExpressions().stream() + .filter(expr -> (expr instanceof Alias) && (expr.child(0) instanceof AggregateFunction)) + .collect(Collectors.toMap(NamedExpression::getExprId, value -> (AggregateFunction) value.child(0))); + Set<AggregateFunction> aggregateFunctions = outerAgg.getAggregateFunctions(); + for (AggregateFunction outerFunc : aggregateFunctions) { + if (!(ALLOW_MERGE_AGGREGATE_FUNCTIONS.contains(outerFunc.getName()))) { + return false; + } + if (outerFunc.isDistinct()) { + return false; + } + // not support outerAggFunc: sum(a+1),sum(a+b) + if (!(outerFunc.child(0) instanceof SlotReference)) { + return false; + } + ExprId childExprId = ((SlotReference) outerFunc.child(0)).getExprId(); + if (innerAggExprIdToAggFunc.containsKey(childExprId)) { + AggregateFunction innerFunc = innerAggExprIdToAggFunc.get(childExprId); + if (innerFunc.isDistinct()) { + return false; + } + // support sum(sum),min(min),max(max),sum(count),any_value(any_value) + if (!(outerFunc.getName().equals("sum") && innerFunc.getName().equals("count")) + && !innerFunc.getName().equals(outerFunc.getName())) { + return false; + } + } else { + if (!outerFunc.getName().equals("max") + && !outerFunc.getName().equals("min") + && !outerFunc.getName().equals("any_value")) { + return false; Review Comment: could u add some comment to explain this else branch? -- 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: commits-unsubscr...@doris.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org For additional commands, e-mail: commits-h...@doris.apache.org