随便写点技术性的文章
TimescaleDB是基于PostgreSQL的时序数据库插件,完全继承了PostgreSQL的功能,TimescaleDB是一个开放源代码的时间序列数据库,针对快速提取和复杂查询进行了优化。它使用“完整的SQL”,并且与传统的关系数据库一样易于使用,但是扩展的方式以前只适用于NoSQL数据库。与这两种方案(关系型和NoSQL)所要求的权衡相比,TimescaleDB为时间序列数据提供了两种方案的最佳选择:
docker pull timescale/timescaledb:latest-pg14
docker pull timescale/timescaledb-postgis:latest-pg13
docker run -d \
--name timescale-test \
-p 5432:5432 \
-e POSTGRES_PASSWORD=123456 \
timescale/timescaledb-postgis:latest-pg13
传感器信息
表名: sensors
Column | Type | Modifiers |
---|---|---|
id | bigint | |
type | text | |
location | text |
传感器记录数据
表名: sensor_data
Column | Type | Modifiers |
---|---|---|
time | timestamp | not null |
sensor_id | bigint | |
temperature | double precision | |
cpu | double precision |
-- 创建 传感器 表
CREATE TABLE sensors(
id SERIAL PRIMARY KEY,
type VARCHAR(50),
location VARCHAR(50)
);
-- 创建 传感器记录 表
CREATE TABLE sensor_data (
time TIMESTAMPTZ NOT NULL,
sensor_id INTEGER,
temperature DOUBLE PRECISION,
cpu DOUBLE PRECISION,
FOREIGN KEY (sensor_id) REFERENCES sensors (id)
);
-- 创建超级表
SELECT create_hypertable('sensor_data', 'time');
-- 插入 传感器 数据
INSERT INTO sensors (type, location) VALUES
('a','floor'),
('a', 'ceiling'),
('b','floor'),
('b', 'ceiling');
-- 插入 传感器记录 数据
INSERT INTO sensor_data (time, sensor_id, cpu, temperature)
SELECT
time,
sensor_id,
random() AS cpu,
random()*100 AS temperature
FROM generate_series(now() - interval '24 hour', now(), interval '5 minute') AS g1(time), generate_series(1,4,1) AS g2(sensor_id);
-- 查询所有数据
SELECT * FROM sensor_data ORDER BY time;
-- 30分钟 温度[平均值] CPU使用率[平均值]
SELECT
time_bucket('30 minutes', time) AS period,
AVG(temperature) AS avg_temp,
AVG(cpu) AS avg_cpu
FROM sensor_data
GROUP BY period;
-- 30分钟 温度[平均值][最新] CPU使用率[平均值]
SELECT
time_bucket('30 minutes', time) AS period,
AVG(temperature) AS avg_temp,
last(temperature, time) AS last_temp,
AVG(cpu) AS avg_cpu
FROM sensor_data
GROUP BY period;
-- 联表查询
SELECT
sensors.location,
time_bucket('30 minutes', time) AS period,
AVG(temperature) AS avg_temp,
last(temperature, time) AS last_temp,
AVG(cpu) AS avg_cpu
FROM sensor_data JOIN sensors on sensor_data.sensor_id = sensors.id
GROUP BY period, sensors.location;
--
SELECT show_shunks();
SELECT show_chunks('sensor_data');
SELECT drop_chunks('2017-01-01'::TIMESTAMPTZ, 'sensor_data');
因为Timescale只是一个PostgreSQL的插件,所以,我们选择一个pg数据库的客户端即可,选择很多.
go get github.com/jackc/pgx/v4
go get -u gorm.io/driver/postgres
go get -u gorm.io/gorm
go get -d entgo.io/ent/cmd/ent