Skip to content

Commit e261127

Browse files
committed
feat(sql): Speed up LatestForecast via better indexing
1 parent 6599b35 commit e261127

File tree

2 files changed

+23
-13
lines changed

2 files changed

+23
-13
lines changed

internal/server/postgres/sql/migrations/00004_predictions.sql

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ CREATE TABLE pred.forecasts (
125125
PRIMARY KEY (forecast_uuid),
126126
UNIQUE (geometry_uuid, source_type_id, forecaster_id, init_time_utc)
127127
);
128-
CREATE INDEX ON pred.forecasts USING GIST (target_period);
128+
CREATE INDEX idx_forecasts_filter ON pred.forecasts USING GIST (geometry_uuid, source_type_id, target_period);
129129

130130
/*
131131
* Table to store predicted generation values.

internal/server/postgres/sql/queries/predictions.sql

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -106,23 +106,33 @@ INSERT INTO pred.predicted_generation_values (
106106
* and source type made by all forecasters. Only forecasts that are older than the pivot time
107107
* minus the specified horizon are considered.
108108
*/
109+
WITH latest_forecasts AS (
110+
SELECT DISTINCT ON (f.forecaster_id)
111+
f.forecast_uuid,
112+
f.init_time_utc,
113+
f.source_type_id,
114+
f.geometry_uuid,
115+
f.forecaster_id
116+
FROM pred.forecasts AS f
117+
WHERE f.geometry_uuid = $1
118+
AND f.source_type_id = $2
119+
AND f.init_time_utc
120+
<= sqlc.arg(pivot_timestamp)::TIMESTAMP - MAKE_INTERVAL(mins => sqlc.arg(horizon_mins)::INTEGER)
121+
AND f.target_period @> sqlc.arg(pivot_timestamp)::TIMESTAMP
122+
ORDER BY
123+
f.forecaster_id ASC,
124+
f.forecast_uuid DESC
125+
)
126+
-- Only join to forecaster table to sort by name once forecasts have been filtered
109127
SELECT DISTINCT ON (fr.forecaster_name)
110-
f.forecast_uuid,
111-
f.init_time_utc,
112-
f.source_type_id,
113-
f.geometry_uuid,
128+
lf.*,
114129
fr.forecaster_name,
115130
fr.forecaster_version,
116-
UUIDV7_EXTRACT_TIMESTAMP(f.forecast_uuid) AS created_at_utc
117-
FROM pred.forecasts AS f
131+
UUIDV7_EXTRACT_TIMESTAMP(lf.forecast_uuid) AS created_at_utc
132+
FROM latest_forecasts AS lf
118133
INNER JOIN pred.forecasters AS fr USING (forecaster_id)
119-
WHERE f.geometry_uuid = $1
120-
AND f.source_type_id = $2
121-
AND f.init_time_utc <= sqlc.arg(pivot_timestamp)::TIMESTAMP - MAKE_INTERVAL(mins => sqlc.arg(horizon_mins)::INTEGER)
122-
AND f.target_period @> sqlc.arg(pivot_timestamp)::TIMESTAMP
123134
ORDER BY
124-
fr.forecaster_name ASC,
125-
f.init_time_utc DESC;
135+
fr.forecaster_name ASC;
126136

127137
-- name: ListForecasts :many
128138
/* ListForecasts retrieves all the forecasts for a given location, source type, and forecaster

0 commit comments

Comments
 (0)