You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[FEATURE] Support eval-style expressions inside stats command in PPL. #3949
Currently, OpenSearch PPL (stats command) does not support inline eval-style expressions, such as conditional aggregation using functions like if() or case(). In tools like Splunk, it is common to write expressions such as:
... | stats count(eval(status="200")) as success_count, count(eval(status="400")) as bad_request_count
... | stats sum(eval(duration * 2)) as total_doubled_duration
This allows users to write intuitive conditional aggregations without needing to add an extra eval stage.
One of the use cases that customer reported is the following:
Index=xxxx
| stats count avg(duration) as “Average Request Duration (MS)” count)eval(http_status LIKE “0%)) as “Zero” count(eval(http_status LIKE “2%”)) as “TwoX” count(eval(http_status_status LIKE “3%”)) as “ThreeX” count(eval(http_status LIKE “4%”)) as “FourX” count(eval(http_status LIKE “5%”)) as “FiveX”
| eval 0% = round ((Zero/count),4*)*100
| eval 2xx% = round ((TwoX/count),4*)*100
| eval 3xx% = round ((ThreeX/count),4*)*100
| eval 4xx% = round ((FourX/count),4*)*100
| eval 5xx% = round ((FiveX/count),4*)*100
| fields “Average Request Duration (MS)” 2xx% 3xx% 4xx% 5xx%
Rewrite to COUNT(*) FILTER(WHERE ...) is preferred because of clearer semantics and easier pushdown to the DSL (what the V2 engine does below). However this requires eval expression is a predicate and cannot support coercion like count(eval(if(a, 1, 0))
Additionally, I ran more tests with SUM to explore a generic way of supporting eval expressions. However, the results show that predicate cases behave differently, and it seems we need handling for different aggregation functions.
sum(eval(predicate))
Boolean values are coerced to 0/1.
Equivalent in SQL: SUM(CASE WHEN predicate THEN 1 ELSE 0 END).
sum(eval(arithmetic))
Sums the expression (ignoring nulls).
Equivalent in SQL: SUM(expr).
| ... | stats sum(eval(age < 40)) as cnt
cnt=1
| ... | stats sum(eval(age + 10)) as cnt
cnt=104
Similar test for DISTINCT_COUNT also show different behavior:
Calcite does support COUNT(expr) on both predicate and arithmetic expressions. However, the semantics differ for COUNT(predicate): it counts all non-null values, regardless of whether the predicate evaluates to true or false.
0: jdbc:calcite:model=src/test/resources/mode> SELECT * FROM emps;
+-------+-------+--------+--------+---------------+-------+------+---------+---------+------------+
| EMPNO | NAME | DEPTNO | GENDER | CITY | EMPID | AGE | SLACKER | MANAGER | JOINEDAT |
+-------+-------+--------+--------+---------------+-------+------+---------+---------+------------+
| 100 | Fred | 10 | | | 30 | 25 | true | false | 1996-08-03 |
| 110 | Eric | 20 | M | San Francisco | 3 | 80 | | false | 2001-01-01 |
| 110 | John | 40 | M | Vancouver | 2 | null | false | true | 2002-05-03 |
| 120 | Wilma | 20 | F | | 1 | 5 | | true | 2005-09-07 |
| 130 | Alice | 40 | F | Vancouver | 2 | null | false | true | 2007-01-01 |
+-------+-------+--------+--------+---------------+-------+------+---------+---------+------------+
0: jdbc:calcite:model=src/test/resources/mode> SELECT COUNT(age < 30) FROM emps;
+--------+
| EXPR$0 |
+--------+
| 3 |
+--------+
0: jdbc:calcite:model=src/test/resources/mode> EXPLAIN PLAN FOR SELECT COUNT(age < 30) FROM emps;
+------------------------------------------------------------------------------------------+
| PLAN |
+------------------------------------------------------------------------------------------+
| EnumerableAggregate(group=[{}], EXPR$0=[COUNT($0)])
EnumerableCalc(expr#0..9=[{inputs}], expr#10=[30], expr#11=[<($t6, $t10)], $f0=[$t11])
EnumerableTableScan(table=[[SALES, EMPS]])
|
+------------------------------------------------------------------------------------------+
Both FILTER (WHERE ...) and CASE WHEN ... translate to the same optimized plan in Calcite:
0: jdbc:calcite:model=src/test/resources/mode> EXPLAIN PLAN FOR SELECT COUNT(1) FILTER(WHERE age < 30) FROM emps;
+-------------------------------------------------------------------------------------------------------------------+
| PLAN |
+-------------------------------------------------------------------------------------------------------------------+
| EnumerableAggregate(group=[{}], EXPR$0=[COUNT() FILTER $0])
EnumerableCalc(expr#0..9=[{inputs}], expr#10=[30], expr#11=[<($t6, $t10)], expr#12=[IS TRUE($t11)], $f1=[$t12])
EnumerableTableScan(table=[[SALES, EMPS]])
|
+-------------------------------------------------------------------------------------------------------------------+
0: jdbc:calcite:model=src/test/resources/mode> EXPLAIN PLAN FOR SELECT COUNT(CASE WHEN age < 30 THEN 1 END) FROM emps;
+-------------------------------------------------------------------------------------------------------------------+
| PLAN |
+-------------------------------------------------------------------------------------------------------------------+
| EnumerableAggregate(group=[{}], EXPR$0=[COUNT() FILTER $0])
EnumerableCalc(expr#0..9=[{inputs}], expr#10=[30], expr#11=[<($t6, $t10)], expr#12=[IS TRUE($t11)], $f1=[$t12])
EnumerableTableScan(table=[[SALES, EMPS]])
|
+-------------------------------------------------------------------------------------------------------------------+
Tried to translate to COUNT() FILTER(WHERE ...) directly but encountered exception. The root cause is we don't consider fields in FILTER clause when "trimming" query plan. See exception below
As workaround, convert to CASE statement instead which worked.
field [SAL] not found; input fields are: [] java.lang.IllegalArgumentException: field [SAL] not found; input fields are: [] at org.apache.calcite.tools.RelBuilder.field(RelBuilder.java:547) at
org.apache.calcite.tools.RelBuilder.field(RelBuilder.java:530) at org.opensearch.sql.calcite.CalciteRexNodeVisitor.lambda$visitQualifiedName$9(CalciteRexNodeVisitor.java:334) at
java.base/java.util.Optional.orElseGet(Optional.java:364) at ...
org.opensearch.sql.calcite.CalciteRelNodeVisitor.resolveAttributesForAggregation(CalciteRelNodeVisitor.java:616) at
org.opensearch.sql.calcite.CalciteRelNodeVisitor.aggregateWithTrimming(CalciteRelNodeVisitor.java:597) at
org.opensearch.sql.calcite.CalciteRelNodeVisitor.visitAggregation(CalciteRelNodeVisitor.java:636) at
org.opensearch.sql.calcite.CalciteRelNodeVisitor.visitAggregation(CalciteRelNodeVisitor.java:122) at
org.opensearch.sql.ast.tree.Aggregation.accept(Aggregation.java:71) at
org.opensearch.sql.ast.AbstractNodeVisitor.visitChildren(AbstractNodeVisitor.java:98) at
org.opensearch.sql.calcite.CalciteRelNodeVisitor.visitProject(CalciteRelNodeVisitor.java:192) at
org.opensearch.sql.calcite.CalciteRelNodeVisitor.visitProject(CalciteRelNodeVisitor.java:122) at
org.opensearch.sql.ast.tree.Project.accept(Project.java:65) at
org.opensearch.sql.calcite.CalciteRelNodeVisitor.analyze(CalciteRelNodeVisitor.java:133) at
org.opensearch.sql.ppl.calcite.CalcitePPLAbstractTest.getRelNode(CalcitePPLAbstractTest.java:88) at
org.opensearch.sql.ppl.calcite.CalcitePPLAggregationTest.testEvalCount(CalcitePPLAggregationTest.java:38) at
...
Activity
LantaoJin commentedon Aug 11, 2025
@vamsimanohar are you still working on this?
dai-chen commentedon Aug 13, 2025
I'm doing gap analysis and estimation for aggregation functions in P1. To avoid overlap, is anyone working on this?
dai-chen commentedon Aug 15, 2025
Implementation Options
count(eval)COUNT(CASE WHEN ...)COUNT(*) FILTER(WHERE ...)is preferred because of clearer semantics and easier pushdown to the DSL (what the V2 engine does below). However this requires eval expression is a predicate and cannot support coercion likecount(eval(if(a, 1, 0))opensearchsql> .... SELECT .... COUNT(*) FILTER(WHERE gender = 'M'), .... AVG(age) FILTER(WHERE gender = 'F') .... FROM accounts; fetched rows / total rows = 1/1 +---------------------------------------+---------------------------------------+ | COUNT(*) FILTER(WHERE gender = 'M') | AVG(age) FILTER(WHERE gender = 'F') | |---------------------------------------+---------------------------------------| | 3 | 32.0 | +---------------------------------------+---------------------------------------+ curl -s -H "Content-Type: application/json" \ -X POST "http://localhost:9200/_plugins/_sql/_explain" \ -d "{\"query\":\"SELECT COUNT(*) FILTER(WHERE gender = 'M'), AVG(age) FILTER(WHERE gender = 'F') FROM accounts;\"}" { "root": { "name": "ProjectOperator", "description": { "fields": "[COUNT(*) FILTER(WHERE gender = 'M'), AVG(age) FILTER(WHERE gender = 'F')]" }, "children": [ { "name": "OpenSearchIndexScan", "description": { "request": "OpenSearchQueryRequest(indexName=accounts, sourceBuilder= {\"from\":0,\"size\":0,\"timeout\":\"1m\", \"aggregations\":{ \"COUNT(*) FILTER(WHERE gender = 'M')\": {\"filter\":{\"term\":{\"gender.keyword\":{\"value\":\"M\",\"boost\":1.0}}}, \"aggregations\":{\"COUNT(*) FILTER(WHERE gender = 'M')\":{\"value_count\":{\"field\":\"_index\"}}}}, \"AVG(age) FILTER(WHERE gender = 'F')\": {\"filter\":{\"term\":{\"gender.keyword\":{\"value\":\"F\",\"boost\":1.0}}}, \"aggregations\":{\"AVG(age) FILTER(WHERE gender = 'F')\":{\"avg\":{\"field\":\"age\"}}}}}}, needClean=true, searchDone=false, pitId=null, cursorKeepAlive=null, searchAfter=null, searchResponse=null)" }, "children": [] } ] } }Ref: https://github.com/opensearch-project/sql/blob/main/docs/user/dql/aggregations.rst#filter-clause
dai-chen commentedon Aug 19, 2025
Proposal
count(eval(predicate)), which covers the most common use case.count(eval(arithmetic)).(FILTER (WHERE ...))is more straightforward and should be preferred.FILTER (WHERE ... IS NOT NULL).SPL Test
Based on additional tests in Splunk SPL:
count(eval(predicate))COUNT(*) FILTER (WHERE predicate).count(eval(arithmetic))COUNT(expr).Additionally, I ran more tests with
SUMto explore a generic way of supporting eval expressions. However, the results show that predicate cases behave differently, and it seems we need handling for different aggregation functions.sum(eval(predicate))SUM(CASE WHEN predicate THEN 1 ELSE 0 END).sum(eval(arithmetic))SUM(expr).Similar test for
DISTINCT_COUNTalso show different behavior:Calcite Test
Calcite does support
COUNT(expr)on both predicate and arithmetic expressions. However, the semantics differ forCOUNT(predicate): it counts all non-null values, regardless of whether the predicate evaluates to true or false.0: jdbc:calcite:model=src/test/resources/mode> SELECT * FROM emps; +-------+-------+--------+--------+---------------+-------+------+---------+---------+------------+ | EMPNO | NAME | DEPTNO | GENDER | CITY | EMPID | AGE | SLACKER | MANAGER | JOINEDAT | +-------+-------+--------+--------+---------------+-------+------+---------+---------+------------+ | 100 | Fred | 10 | | | 30 | 25 | true | false | 1996-08-03 | | 110 | Eric | 20 | M | San Francisco | 3 | 80 | | false | 2001-01-01 | | 110 | John | 40 | M | Vancouver | 2 | null | false | true | 2002-05-03 | | 120 | Wilma | 20 | F | | 1 | 5 | | true | 2005-09-07 | | 130 | Alice | 40 | F | Vancouver | 2 | null | false | true | 2007-01-01 | +-------+-------+--------+--------+---------------+-------+------+---------+---------+------------+ 0: jdbc:calcite:model=src/test/resources/mode> SELECT COUNT(age < 30) FROM emps; +--------+ | EXPR$0 | +--------+ | 3 | +--------+ 0: jdbc:calcite:model=src/test/resources/mode> EXPLAIN PLAN FOR SELECT COUNT(age < 30) FROM emps; +------------------------------------------------------------------------------------------+ | PLAN | +------------------------------------------------------------------------------------------+ | EnumerableAggregate(group=[{}], EXPR$0=[COUNT($0)]) EnumerableCalc(expr#0..9=[{inputs}], expr#10=[30], expr#11=[<($t6, $t10)], $f0=[$t11]) EnumerableTableScan(table=[[SALES, EMPS]]) | +------------------------------------------------------------------------------------------+Both
FILTER (WHERE ...)andCASE WHEN ...translate to the same optimized plan in Calcite:0: jdbc:calcite:model=src/test/resources/mode> EXPLAIN PLAN FOR SELECT COUNT(1) FILTER(WHERE age < 30) FROM emps; +-------------------------------------------------------------------------------------------------------------------+ | PLAN | +-------------------------------------------------------------------------------------------------------------------+ | EnumerableAggregate(group=[{}], EXPR$0=[COUNT() FILTER $0]) EnumerableCalc(expr#0..9=[{inputs}], expr#10=[30], expr#11=[<($t6, $t10)], expr#12=[IS TRUE($t11)], $f1=[$t12]) EnumerableTableScan(table=[[SALES, EMPS]]) | +-------------------------------------------------------------------------------------------------------------------+ 0: jdbc:calcite:model=src/test/resources/mode> EXPLAIN PLAN FOR SELECT COUNT(CASE WHEN age < 30 THEN 1 END) FROM emps; +-------------------------------------------------------------------------------------------------------------------+ | PLAN | +-------------------------------------------------------------------------------------------------------------------+ | EnumerableAggregate(group=[{}], EXPR$0=[COUNT() FILTER $0]) EnumerableCalc(expr#0..9=[{inputs}], expr#10=[30], expr#11=[<($t6, $t10)], expr#12=[IS TRUE($t11)], $f1=[$t12]) EnumerableTableScan(table=[[SALES, EMPS]]) | +-------------------------------------------------------------------------------------------------------------------+dai-chen commentedon Aug 19, 2025
Proof of Concept
Functional Support
COUNT() FILTER(WHERE ...)directly but encountered exception. The root cause is we don't consider fields inFILTERclause when "trimming" query plan. See exception belowCASEstatement instead which worked.opensearchsql> source=accounts; fetched rows / total rows = 5/5 +----------+------------------+-------+ | gender | account_number | age | |----------+------------------+-------| | M | 1 | 31 | | F | 2 | 26 | | M | 3 | 45 | | F | 4 | 38 | | M | 5 | 29 | +----------+------------------+-------+ opensearchsql> source=accounts | stats count(eval(age > 30)) as cnt; fetched rows / total rows = 1/1 +-------+ | cnt | |-------| | 3 | +-------+ opensearchsql> explain source=accounts | stats count(eval(age > 30)) as cnt; OpenSearchException({'calcite': { 'logical': 'LogicalSystemLimit(fetch=[10000], type=[QUERY_SIZE_LIMIT])\n LogicalAggregate(group=[{}], cnt=[COUNT($0)])\n LogicalProject($f1=[CASE(>($2, 30), 1, null:NULL)])\n CalciteLogicalIndexScan(table=[[OpenSearch, accounts]])\n', 'physical': 'EnumerableLimit(fetch=[10000])\n EnumerableAggregate(group=[{}], cnt=[COUNT() FILTER $0])\n EnumerableCalc(expr#0=[{inputs}], expr#1=[30], expr#2=[>($t0, $t1)], expr#3=[IS TRUE($t2)], $f0=[$t3])\n CalciteEnumerableIndexScan(table=[[OpenSearch, accounts]], PushDownContext=[[PROJECT->[age]], OpenSearchRequestBuilder(sourceBuilder={"from":0,"timeout":"1m","_source":{"includes":["age"],"excludes":[]}}, requestedTotalSize=2147483647, pageSize=null, startFrom=0)])\n'}})Pushdown Optimization
TODO