Skip to content

Support pushing down date_trunc(<unit>, ts) dyn filter to the downstream operators #25327

Description

@niebayes

For a query that aggregates by date_trunc(<unit>, ts) and takes the top-K groups by the same expression, e.g.

SELECT date_trunc('minute', ts) AS minute, max(usage_user)
FROM cpu
WHERE ts < '2016-01-01T14:41:34Z'
GROUP BY minute
ORDER BY minute DESC
LIMIT 5;

the SortExec (TopK fetch=5) builds a DynamicFilterPhysicalExpr on minute. Even though minute is exactly the aggregate's grouping expression, this dynamic filter is not pushed down past the AggregateExec to the scan. As a result the scan reads the entire input instead of only the newest minute buckets. This is the dominant cost for TSBS benchmark case groupby-orderby-limit.

Expected behavior

The TopK filter on the grouping expression should be pushed below the aggregate (and below the projection), because it only selects which groups to compute — each group's aggregate value is identical whether the filter is applied before or after grouping. Ideally the filter should also be rewritten so a scan can evaluate it, i.e. the predicate on

date_trunc(k, ts) <cmp> X

should be exposed as an equivalent predicate on the base column ts, using monotonicity of date_trunc:

filter on date_trunc(k, ts) equivalent on ts
> X ts >= X + k
>= X ts >= X
< X ts < X
<= X ts < X + k

This is exactly the "top-K by time bucket" pattern, where only the newest N buckets need to be scanned.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions