Skip to content

Commit ce9ff12

Browse files
committed
Run single phase aggregation when possible
1 parent 221998d commit ce9ff12

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/PhysicalPlanOptimizer.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import org.elasticsearch.xpack.esql.VerificationException;
1111
import org.elasticsearch.xpack.esql.common.Failures;
1212
import org.elasticsearch.xpack.esql.optimizer.rules.physical.ProjectAwayColumns;
13+
import org.elasticsearch.xpack.esql.optimizer.rules.physical.SinglePhaseAggregate;
1314
import org.elasticsearch.xpack.esql.plan.physical.FragmentExec;
1415
import org.elasticsearch.xpack.esql.plan.physical.PhysicalPlan;
1516
import org.elasticsearch.xpack.esql.rule.ParameterizedRuleExecutor;
@@ -24,7 +25,7 @@
2425
public class PhysicalPlanOptimizer extends ParameterizedRuleExecutor<PhysicalPlan, PhysicalOptimizerContext> {
2526

2627
private static final List<RuleExecutor.Batch<PhysicalPlan>> RULES = List.of(
27-
new Batch<>("Plan Boundary", Limiter.ONCE, new ProjectAwayColumns())
28+
new Batch<>("Plan Boundary", Limiter.ONCE, new ProjectAwayColumns(), new SinglePhaseAggregate())
2829
);
2930

3031
private final PhysicalVerifier verifier = PhysicalVerifier.INSTANCE;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License
4+
* 2.0; you may not use this file except in compliance with the Elastic License
5+
* 2.0.
6+
*/
7+
8+
package org.elasticsearch.xpack.esql.optimizer.rules.physical;
9+
10+
import org.elasticsearch.compute.aggregation.AggregatorMode;
11+
import org.elasticsearch.xpack.esql.plan.physical.AggregateExec;
12+
import org.elasticsearch.xpack.esql.plan.physical.PhysicalPlan;
13+
import org.elasticsearch.xpack.esql.rule.Rule;
14+
15+
/**
16+
* Collapses two-phase aggregation into a single phase when possible.
17+
* For example, in FROM .. | STATS first | STATS second, the STATS second aggregation
18+
* can be executed in a single phase on the coordinator instead of two phases.
19+
*/
20+
public class SinglePhaseAggregate extends Rule<PhysicalPlan, PhysicalPlan> {
21+
@Override
22+
public PhysicalPlan apply(PhysicalPlan plan) {
23+
if (plan instanceof AggregateExec parent
24+
&& parent.getMode() == AggregatorMode.INITIAL
25+
&& parent.child() instanceof AggregateExec child
26+
&& child.getMode() == AggregatorMode.FINAL) {
27+
return parent.withMode(AggregatorMode.SINGLE).replaceChild(child.child());
28+
}
29+
return plan;
30+
}
31+
}

0 commit comments

Comments
 (0)