Skip to content

Instantly share code, notes, and snippets.

@martyndavies
Created April 6, 2018 16:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martyndavies/e61ce1be6a2620ee1e62c5114758b997 to your computer and use it in GitHub Desktop.
Save martyndavies/e61ce1be6a2620ee1e62c5114758b997 to your computer and use it in GitHub Desktop.
Example of a Postgres rollup
CREATE OR REPLACE FUNCTION compute_5min_rollups(start_time TIMESTAMP, end_time TIMESTAMP)
RETURNS void LANGUAGE PLPGSQL AS $function$
BEGIN
EXECUTE $$
INSERT INTO rollups_5min
SELECT
date_trunc('seconds', (timestamp - TIMESTAMP 'epoch') / 300) * 300 + TIMESTAMP 'epoch' AS minute,
app_id,
timestamp,
count(*) AS query_count,
hll_add_agg(hll_hash_bigint(user_id)) AS user_count,
topn_add_agg(query) AS top_queries
FROM queries
WHERE timestamp >= $1 AND timestamp <= $2
GROUP BY app_id, minute; $$
USING start_time, end_time;
END;
$function$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment