Skip to content

PPL: avg() on DATE/TIMESTAMP field fails instead of implicitly casting to numeric #5131

@ahkcs

Description

@ahkcs

Description

When using avg() on a DATE/TIMESTAMP field followed by arithmetic operations and ROUND(), the query fails with an ExpressionEvaluationException. The avg() aggregation rejects DATE/TIMESTAMP fields upfront because it only accepts NUMERIC operand types.

Failing Query

source=opensearch_dashboards_sample_data_logs
| stats count() as Request_Count, avg(`response`) as avg_response by `response`
| eval success_rate = (avg_response/Request_Count)
| fields success_rate, Request_Count, response
| eval rounded_success_rate = ROUND(success_rate, 2)
| fields rounded_success_rate

Error

{
  "error": {
    "reason": "Invalid Query",
    "details": "Aggregation function AVG expects field type {[INTEGER]|[DOUBLE]}, but got [TIMESTAMP]",
    "type": "ExpressionEvaluationException"
  },
  "status": 400
}

Root Cause

NullableSqlAvgAggFunction uses OperandTypes.NUMERIC which rejects DATE/TIMESTAMP fields. The avg() call fails before any downstream arithmetic is reached.

Key Files

  • core/src/main/java/org/opensearch/sql/calcite/udf/udaf/NullableSqlAvgAggFunction.java — avg() operand validation
  • core/src/main/java/org/opensearch/sql/expression/function/PPLFuncImpTable.java — avg() registration

Proposed Fix

Extend avg() to accept DATE/TIMESTAMP fields by implicitly casting them to BIGINT (epoch millis) before averaging, so the result is numeric (DOUBLE). This allows downstream arithmetic and ROUND() to work naturally.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions