Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Apache Druid Aggregate Macro

From Leeroopedia


Knowledge Sources
Domains Web_Console, Explore_View
Last Updated 2026-02-10 10:00 GMT

Overview

Rewrites AGGREGATE macro function calls in SQL queries by substituting named measure definitions with their actual aggregate expressions.

Description

The Aggregate Macro module provides a single `rewriteAggregate` function that walks a SQL AST tree looking for calls to the special `AGGREGATE(measureName)` macro function. When found, it resolves the measure name against a provided list of Measure objects and replaces the macro with the measure's actual aggregate expression (e.g., SUM, COUNT, etc.). If the AGGREGATE call includes a WHERE filter, that filter is applied to the underlying aggregation. After rewriting, the function also ensures that any columns referenced by used measures are included in the SELECT list of the source sub-query.

Usage

Used during query execution in the explore view to transform template queries containing AGGREGATE macros into executable SQL by inlining the user-configured measure definitions.

Code Reference

Source Location

Signature

export function rewriteAggregate(query: SqlQuery, measures: Measure[]): SqlQuery;

Import

import { rewriteAggregate } from '../query-macros/aggregate';

I/O Contract

Inputs

Name Type Required Description
query SqlQuery Yes A SQL query AST potentially containing AGGREGATE(...) macro function calls
measures Measure[] Yes The list of available Measure definitions with names and aggregate expressions

Outputs

Name Type Description
(return) SqlQuery The rewritten SQL query with all AGGREGATE macros replaced by their actual aggregate expressions

Usage Examples

Rewrite AGGREGATE macros in a query

import { rewriteAggregate } from '../query-macros/aggregate';
import { SqlQuery } from 'druid-query-toolkit';

const query = SqlQuery.parse(`
  SELECT
    TIME_FLOOR(__time, 'PT1H') AS "time",
    AGGREGATE('total_count') AS "cnt"
  FROM "wikipedia"
  GROUP BY 1
`);

const measures = [
  { name: 'total_count', expression: SqlFunction.COUNT_STAR },
];

const rewritten = rewriteAggregate(query, measures);
// AGGREGATE('total_count') is replaced with COUNT(*)

AGGREGATE with a WHERE filter

// AGGREGATE('total_count') FILTER (WHERE channel = 'en')
// Becomes: COUNT(*) FILTER (WHERE channel = 'en')

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment