Browse Source

ES|QL: Fix stats by constant expression (#114899) (#115087)

Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
Luigi Dell'Aquila 11 months ago
parent
commit
53184053e3

+ 5 - 0
docs/changelog/114899.yaml

@@ -0,0 +1,5 @@
+pr: 114899
+summary: "ES|QL: Fix stats by constant expression"
+area: ES|QL
+type: bug
+issues: []

+ 29 - 0
x-pack/plugin/esql/qa/testFixtures/src/main/resources/stats.csv-spec

@@ -2473,3 +2473,32 @@ c2:l |c2_f:l |m2:i |m2_f:i |c:l
 1    |0      |2    |2      |19
 1    |1      |5    |5      |21
 ;
+
+
+statsByConstantExpressionNoAggs
+required_capability: fix_stats_by_foldable_expression
+FROM employees | eval x = [1,2,3], y = 5 + 6 | stats by y+1
+;
+
+y+1:integer
+12
+;
+
+
+statsByConstantExpressionNoAggsWithAlias
+required_capability: fix_stats_by_foldable_expression
+FROM employees | eval x = [1,2,3], y = 5 + 6 | stats by yy = y+1
+;
+
+yy:integer
+12
+;
+
+statsByConstantExpression
+required_capability: fix_stats_by_foldable_expression
+FROM employees | eval x = [1,2,3], y = 5 + 6 | stats m = max(y) by y+1
+;
+
+m:integer | y+1:integer
+11        | 12
+;

+ 6 - 1
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/action/EsqlCapabilities.java

@@ -385,7 +385,12 @@ public class EsqlCapabilities {
         /**
          * Allow filter per individual aggregation.
          */
-        PER_AGG_FILTERING;
+        PER_AGG_FILTERING,
+
+        /**
+         * Fix for https://github.com/elastic/elasticsearch/issues/114714
+         */
+        FIX_STATS_BY_FOLDABLE_EXPRESSION;
 
         private final boolean snapshotOnly;
         private final FeatureFlag featureFlag;

+ 8 - 1
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plan/logical/Aggregate.java

@@ -11,6 +11,7 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
 import org.elasticsearch.common.io.stream.StreamInput;
 import org.elasticsearch.common.io.stream.StreamOutput;
 import org.elasticsearch.xpack.esql.core.capabilities.Resolvables;
+import org.elasticsearch.xpack.esql.core.expression.Alias;
 import org.elasticsearch.xpack.esql.core.expression.Attribute;
 import org.elasticsearch.xpack.esql.core.expression.AttributeSet;
 import org.elasticsearch.xpack.esql.core.expression.Expression;
@@ -157,7 +158,13 @@ public class Aggregate extends UnaryPlan implements Stats {
     }
 
     public static AttributeSet computeReferences(List<? extends NamedExpression> aggregates, List<? extends Expression> groupings) {
-        return Expressions.references(groupings).combine(Expressions.references(aggregates));
+        AttributeSet result = Expressions.references(groupings).combine(Expressions.references(aggregates));
+        for (Expression grouping : groupings) {
+            if (grouping instanceof Alias) {
+                result.remove(((Alias) grouping).toAttribute());
+            }
+        }
+        return result;
     }
 
     @Override