timescaledb/notes.md
2026-03-12 19:41:44 +01:00

2.3 KiB

timescaledb

https://github.com/timescale/timescaledb

Test

Récup datas

ssh grab-4
docker exec client-demo-postgres-1 pg_dump -Fc -U postgres postgres > /tmp/backup_postgres.dump
exit

cd /tmp
scp grab-4:/tmp/backup_postgres.dump .
pg_restore -c -x -t mesure -d postgres -h localhost -U postgres -W  backup_postgres.dump
pg_restore -c -x -I mesure_idx1 -d postgres -h localhost -U postgres -W  backup_postgres.dump
pg_restore -c -x -I mesure_idx2 -d postgres -h localhost -U postgres -W  backup_postgres.dump

Création d'une hypertable

CREATE TABLE mesure_ng (
  "date" TIMESTAMPTZ,
  id_captation INT NOT NULL,
  valeur float4 NOT NULL
) WITH (
  tsdb.hypertable,
  timescaledb.segmentby = 'id_captation',
  timescaledb.orderby='date DESC'
)

INSERT INTO mesure_ng ("date", id_captation, valeur)
  SELECT "date", id_captation, valeur
    FROM mesure

Compression des données (stockage en colonnes)

SELECT add_columnstore_policy('mesure_ng', INTERVAL '15 days')

Ex. de requête

SELECT
  time_bucket('1 hour', "date") AS heure,
  round(
    average(
      time_weight('linear', "date", valeur)
    )
  ) AS moyenne_conso,
  COUNT(*) AS nombre_de_mesures
FROM
  mesure_ng
WHERE
  "date" BETWEEN '2026-03-01 00:00:00' AND '2026-03-31 23:59:59'
  and id_captation = 59 -- puissance PAC
GROUP BY
  heure
ORDER BY
  heure;

Exploit

SELECT *
FROM timescaledb_information.chunks
WHERE hypertable_name = 'mesure_ng'

SELECT * FROM timescaledb_information.jobs

Continuous aggregates (WIP)

https://www.tigerdata.com/docs/use-timescale/latest/continuous-aggregates/create-a-continuous-aggregate

  • CREATE MATERIALIZED VIEW
  • CALL add_continuous_aggregate_policy
  • supprimer les "vieilles" données de mesure_ng (add_retention_policy ?)

Exemples

Gauges

CREATE MATERIALIZED VIEW sensor_hourly WITH (timescaledb.continuous) AS SELECT time_bucket('1 hour', time) AS bucket, sensor_id, average( time_weight('linear', "date", valeur) ) AS moyenne_temporelle, percentile_agg(value) AS pct FROM sensor_data GROUP BY bucket, sensor_id;

Puis

SELECT bucket, sensor_id, approx_percentile(0.95, pct) AS p95, approx_percentile(0.99, pct) AS p99 FROM sensor_hourly;

Index

delta(counter_agg(time, value))