Skip to content

[FEATURE] Support eval-style expressions inside stats command in PPL. #3949

Closed

Description

@vamsimanohar

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%

Activity

  1. added
    PPL
    and removed on Jul 31, 2025
  2. moved this from Not Started to In progress in PPL Trackeron Aug 11, 2025
  3. LantaoJin commented on Aug 11, 2025

    @LantaoJin
    Member

    @vamsimanohar are you still working on this?

  4. dai-chen commented on Aug 13, 2025

    @dai-chen
    Collaborator

    I'm doing gap analysis and estimation for aggregation functions in P1. To avoid overlap, is anyone working on this?

  5. dai-chen commented on Aug 15, 2025

    @dai-chen
    Collaborator

    Implementation Options count(eval)

    1. Rewrite to COUNT(CASE WHEN ...)
    2. 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))
    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

  6. dai-chen commented on Aug 19, 2025

    @dai-chen
    Collaborator

    Proposal

    1. Syntax
      • High priority: support count(eval(predicate)), which covers the most common use case.
      • Low priority: support count(eval(arithmetic)).
    2. Data Type
      • Only perform if type match; do not introduce implicit conversions here, e.g., age = "35".
      • Broader type handling will be tracked separately under general support for schemaless.
    3. Implementation
      • Option 1 and Option 2 generate the same physical plan in Calcite after optimization.
      • Option 2 (FILTER (WHERE ...)) is more straightforward and should be preferred.
      • For non-predicate expressions, simply use FILTER (WHERE ... IS NOT NULL).

    SPL Test

    Based on additional tests in Splunk SPL:

    1. count(eval(predicate))
      • Acts as filtered counting, as documented in SPL.
      • Equivalent in SQL: COUNT(*) FILTER (WHERE predicate).
    2. count(eval(arithmetic))
      • Counts non-null results of the expression.
      • Equivalent in SQL: COUNT(expr).
    | makeresults format=json data="[{\"name\":\"John\", \"age\":35}, {\"name\":\"Sarah\", \"age\":49}, {\"name\":\"Hank\"}]" 
    | stats count(eval(age < 40)) as cnt
    -- cnt=1
    
    | ... | stats count(eval(age)) as cnt
    -- cnt=2
    
    | ... | stats count(eval(age + 10)) as cnt
    -- cnt=2
    

    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.

    1. sum(eval(predicate))
      • Boolean values are coerced to 0/1.
      • Equivalent in SQL: SUM(CASE WHEN predicate THEN 1 ELSE 0 END).
    2. 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:

    | makeresults format=json data="[{\"name\":\"John\", \"age\":35}, {\"name\":\"Sarah\", \"age\":49}, {\"name\":\"Hank\"}]" 
    | stats dc(eval(age > 25)) as cnt
    -- cnt=1
    
    ... | stats dc(eval(age > 40)) as cnt
    -- cnt=1
    
    ... | stats dc(eval(age > 49)) as cnt
    -- cnt=0
    
    # Equivalent Calcite SQL query, however Calcite doesn't support `count(distinct case when...)`
    0: jdbc:calcite:model=src/test/resources/mode> SELECT count(distinct 1) filter(where age > 10) FROM emps;
    +--------+
    | EXPR$0 |
    +--------+
    | 1      |
    +--------+
    1 row selected (0.039 seconds)
    0: jdbc:calcite:model=src/test/resources/mode> SELECT count(distinct 1) filter(where age > 100) FROM emps;
    +--------+
    | EXPR$0 |
    +--------+
    | 0      |
    +--------+
    

    Calcite Test

    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]])
     |
    +-------------------------------------------------------------------------------------------------------------------+
    
  7. dai-chen commented on Aug 19, 2025

    @dai-chen
    Collaborator

    Proof of Concept

    Functional Support

    • 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.
    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'}})
    
    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
    ...
    

    Pushdown Optimization

    TODO

  8. moved this from In progress to Done in PPL Trackeron Sep 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

PPLenhancementv3.3.0

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions