时序数据库 TimescaleDB 安装与使用

在这里插入图片描述

TimescaleDB 是一个时间序列数据库,建立在 PostgreSQL 之上。然而,不仅如此,它还是时间序列的关系数据库。使用 TimescaleDB 的开发人员将受益于专门构建的时间序列数据库以及经典的关系数据库 (PostgreSQL),所有这些都具有完整的 SQL 支持。本文介绍 TimescaleDB 的 CentOS 7 环境源码编译安装与使用。

01 源码安装


安装 TimescaleDB 之前确保你的机器上已经安装好了 PostgreSQL,并且检查安装的 PG 版本与 TimescaleDB 版本兼容情况:https://docs.timescale.com/self-hosted/latest/upgrades/upgrade-pg/
在这里插入图片描述
源码安装需要使用到 CMake 和 GUN 编译器 gcc 等工具,确保机器已经安装了这些工具

1.1 源码安装 TimescaleDB

  1. 拉取 TimescaleDB 源码
git clone https://github.com/timescale/timescaledb
  1. 进入源码目录并切换分支到指定版本
cd timescaledb
git checkout 2.11.1
  1. 执行 bootstrap 引导构建系统
./bootstrap 

遇到报错:PostgreSQL was built without OpenSSL support, which TimescaleDB needs for full compatibility
解决方法:重新编译安装 postgresql,增加 --with-openssl 选项
./configure --prefix=/home/randy/soft/postgresql --with-openssl
或者执行 ./bootstrap -DUSE_OPENSSL=0 不使用 openssl
在这里插入图片描述

  1. 进入上一步生成的 build 目录,编译安装 timescaledb
cd build
make && make install

安装完成之后,就可以在 postgresql 插件目录下看到 timescaledb 了
在这里插入图片描述

1.2 修改 PG 配置

完成 TimescaleDB 安装之后,需要修改 postgresql 配置文件增加 timescaledb 预加载库

  1. 找到 pg 配置文件
$ psql -Upostgres -dpostgres -c "SHOW config_file;"
Password for user postgres:config_file
--------------------------------------------------/home/randy/soft/postgresql/data/postgresql.conf
(1 row)
  1. 修改 pg 配置文件
vim /home/randy/soft/postgresql/data/postgresql.conf
# 做如下修改
shared_preload_libraries = 'timescaledb'

修改完成之后重启 pg

1.3 安装 TimescaleDB 插件

  1. 执行如下命令创建 timescaledb 插件
CREATE EXTENSION IF NOT EXISTS timescaledb;
  1. 完成插件创建之后可以使用 \dx 命令查看插件是否成功安装
testdb=# \dxList of installed extensionsName     | Version |   Schema   |                                      Description
-------------+---------+------------+---------------------------------------------------------------------------------------plpgsql     | 1.0     | pg_catalog | PL/pgSQL procedural languagetimescaledb | 2.11.1  | public     | Enables scalable inserts and complex queries for time-series data (Community Edition)
(2 rows)

在这里插入图片描述
至此,postgresql + timescaledb 时序数据库就安装完成了

  1. 不想再用这个插件的话,使用如下命令删除插件
DROP EXTENSION IF EXISTS timescaledb;

02 Timescale 基础使用


2.1 创建超表 hypertables

  1. CREATE 创建一个 pg 普通表
testdb=# CREATE TABLE conditions (time        TIMESTAMPTZ       NOT NULL,location    TEXT              NOT NULL,device      TEXT              NOT NULL,temperature DOUBLE PRECISION  NULL,humidity    DOUBLE PRECISION  NULL
);
CREATE TABLE

然后使用 create_hypertable 函数将普通表转化成 hypertable

testdb=# SELECT create_hypertable('conditions', 'time');create_hypertable
-------------------------(1,public,conditions,t)
(1 row)
  1. INSERT 向 hypertable 中插入数据
testdb=# INSERT INTO conditions(time, location, device, temperature, humidity)
SELECT now(), to_char(i, 'FM0000'), to_char(i, 'FM00000'), random()*i, random()*i FROM generate_series(1,10000) i;
INSERT 0 10000
  1. SELECT 查询 hypertable 数据
testdb=# SELECT * FROM conditions ORDER BY time DESC LIMIT 10;time              | location | device |     temperature     |       humidity
-------------------------------+----------+--------+---------------------+----------------------2023-08-03 12:37:00.345665+08 | 0001     | 00001  | 0.24349980974765373 |   0.59486877297972642023-08-03 12:37:00.345665+08 | 0002     | 00002  |  1.8149739913052656 |    0.6162655023691672023-08-03 12:37:00.345665+08 | 0003     | 00003  |   2.400422475569293 |   0.68700570944077912023-08-03 12:37:00.345665+08 | 0004     | 00004  |   2.639553072461581 |   1.94090348497051932023-08-03 12:37:00.345665+08 | 0005     | 00005  |   2.127623537273031 |   3.88715035379826552023-08-03 12:37:00.345665+08 | 0006     | 00006  |  2.3469833801156312 |    4.4115299335274262023-08-03 12:37:00.345665+08 | 0007     | 00007  |  1.0073460031664823 | 0.0168279977406164962023-08-03 12:37:00.345665+08 | 0008     | 00008  |   7.023014897212306 |   0.86792935440220732023-08-03 12:37:00.345665+08 | 0009     | 00009  |   6.744935559863428 |    6.3129489812979682023-08-03 12:37:00.345665+08 | 0010     | 00010  |   9.279208258323166 |    9.451548543523778
(10 rows)
  1. UPDATE 更新 hypertable 数据

更新数据的语句与标准 SQL 一致,如下示例修改指定记录的值

testdb=# SELECT * FROM conditions
WHERE time = '2023-08-03 12:37:00.345665+08' AND location = '0001';time              | location | device |     temperature     |      humidity
-------------------------------+----------+--------+---------------------+--------------------2023-08-03 12:37:00.345665+08 | 0001     | 00001  | 0.24349980974765373 | 0.5948687729797264
(1 row)testdb=# UPDATE conditions SET temperature = 70.2, humidity = 50.0
WHERE time = '2023-08-03 12:37:00.345665+08' AND location = '0001';
UPDATE 1
testdb=# SELECT * FROM conditions
WHERE time = '2023-08-03 12:37:00.345665+08' AND location = '0001';time              | location | device | temperature | humidity
-------------------------------+----------+--------+-------------+----------2023-08-03 12:37:00.345665+08 | 0001     | 00001  |        70.2 |       50
(1 row)

也可以修改该指定范围内的多行记录,如下例子中修改时间 2023-08-03 12:37:00 到 2023-08-03 12:37:05 这 5 秒内的数据如下

testdb=# SELECT * FROM conditions ORDER BY time DESC LIMIT 10;time              | location | device |    temperature     |       humidity
-------------------------------+----------+--------+--------------------+----------------------2023-08-03 12:37:00.345665+08 | 0002     | 00002  | 1.8149739913052656 |    0.6162655023691672023-08-03 12:37:00.345665+08 | 0003     | 00003  |  2.400422475569293 |   0.68700570944077912023-08-03 12:37:00.345665+08 | 0004     | 00004  |  2.639553072461581 |   1.94090348497051932023-08-03 12:37:00.345665+08 | 0005     | 00005  |  2.127623537273031 |   3.88715035379826552023-08-03 12:37:00.345665+08 | 0006     | 00006  | 2.3469833801156312 |    4.4115299335274262023-08-03 12:37:00.345665+08 | 0007     | 00007  | 1.0073460031664823 | 0.0168279977406164962023-08-03 12:37:00.345665+08 | 0008     | 00008  |  7.023014897212306 |   0.86792935440220732023-08-03 12:37:00.345665+08 | 0009     | 00009  |  6.744935559863428 |    6.3129489812979682023-08-03 12:37:00.345665+08 | 0010     | 00010  |  9.279208258323166 |    9.4515485435237782023-08-03 12:37:00.345665+08 | 0011     | 00011  |  1.994685462372594 |    7.361677356344085
(10 rows)testdb=# UPDATE conditions SET temperature = temperature + 0.1
WHERE time >= '2023-08-03 12:37:00' AND time < '2023-08-03 12:37:05';
UPDATE 10000
testdb=# SELECT * FROM conditions ORDER BY time DESC LIMIT 10;time              | location | device |    temperature     |       humidity
-------------------------------+----------+--------+--------------------+----------------------2023-08-03 12:37:00.345665+08 | 0002     | 00002  | 1.9149739913052657 |    0.6162655023691672023-08-03 12:37:00.345665+08 | 0003     | 00003  |  2.500422475569293 |   0.68700570944077912023-08-03 12:37:00.345665+08 | 0004     | 00004  |  2.739553072461581 |   1.94090348497051932023-08-03 12:37:00.345665+08 | 0005     | 00005  | 2.2276235372730313 |   3.88715035379826552023-08-03 12:37:00.345665+08 | 0006     | 00006  | 2.4469833801156313 |    4.4115299335274262023-08-03 12:37:00.345665+08 | 0007     | 00007  | 1.1073460031664824 | 0.0168279977406164962023-08-03 12:37:00.345665+08 | 0008     | 00008  |  7.123014897212306 |   0.86792935440220732023-08-03 12:37:00.345665+08 | 0009     | 00009  |  6.844935559863428 |    6.3129489812979682023-08-03 12:37:00.345665+08 | 0010     | 00010  |  9.379208258323166 |    9.4515485435237782023-08-03 12:37:00.345665+08 | 0011     | 00011  |  2.094685462372594 |    7.361677356344085
(10 rows)
  1. Upsert 插入新数据或更新已存在的数据

Upsert 只能在存在唯一索引或唯一约束的表中生效,可以使用 ALTER TABLE … ADD CONSTRAINT … UNIQUE 语句为已经存在的 hypertable 创建唯一约束

testdb=# ALTER TABLE conditionsADD CONSTRAINT conditions_time_locationUNIQUE (time, location);
ALTER TABLE
testdb=# \d conditionsTable "public.conditions"Column    |           Type           | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+---------time        | timestamp with time zone |           | not null |location    | text                     |           | not null |device      | text                     |           | not null |temperature | double precision         |           |          |humidity    | double precision         |           |          |
Indexes:"conditions_time_location" UNIQUE CONSTRAINT, btree ("time", location)"conditions_time_idx" btree ("time")
Triggers:ts_insert_blocker BEFORE INSERT ON conditions FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()
Number of child tables: 1 (Use \d+ to list them.)

插入新数据或更新已存在的数据使用 INSERT INTO … VALUES … ON CONFLICT … DO UPDATE 语句实现

testdb=# SELECT * FROM conditions
WHERE time = '2023-08-03 12:37:00.345665+08' AND location = '0001';time              | location | device | temperature | humidity
-------------------------------+----------+--------+-------------+----------2023-08-03 12:37:00.345665+08 | 0001     | 00001  |        70.3 |       50
(1 row)testdb=# INSERT INTO conditions
VALUES ('2023-08-03 12:37:00.345665+08', '0001', '00001', 70.2, 50.1)
ON CONFLICT (time, location) DO UPDATESET temperature = excluded.temperature,humidity = excluded.humidity;
INSERT 0 1
testdb=# SELECT * FROM conditions
WHERE time = '2023-08-03 12:37:00.345665+08' AND location = '0001';time              | location | device | temperature | humidity
-------------------------------+----------+--------+-------------+----------2023-08-03 12:37:00.345665+08 | 0001     | 00001  |        70.2 |     50.1
(1 row)

也可以只执行插入操作,如果记录已存在则直接跳过,该操作使用 INSERT INTO … VALUES … ON CONFLICT DO NOTHING 语句实现

testdb=# INSERT INTO conditionsVALUES (NOW(), 'new', '00001', 70.1, 50.0)ON CONFLICT DO NOTHING;
INSERT 0 1
testdb=# SELECT * FROM conditions WHERE location = 'new';time              | location | device | temperature | humidity
-------------------------------+----------+--------+-------------+----------2023-08-04 10:33:16.698018+08 | new      | 00001  |        70.1 |       50
(1 row)testdb=# INSERT INTO conditions
VALUES ('2023-08-04 10:33:16.698018+08', '0001', '00001', 71, 50.1)
ON CONFLICT DO NOTHING;
INSERT 0 1
testdb=# SELECT * FROM conditions WHERE location = 'new';time              | location | device | temperature | humidity
-------------------------------+----------+--------+-------------+----------2023-08-04 10:33:16.698018+08 | new      | 00001  |        70.1 |       50
(1 row)
  1. DELETE 删除数据

删除数据的语句与标准 SQL 一致 DELETE FROM …

testdb=# SELECT * FROM conditions WHERE location = 'new';time              | location | device | temperature | humidity
-------------------------------+----------+--------+-------------+----------2023-08-04 10:33:16.698018+08 | new      | 00001  |        70.1 |       50
(1 row)testdb=# DELETE FROM conditions WHERE location = 'new';
DELETE 1
testdb=# SELECT * FROM conditions WHERE location = 'new';time | location | device | temperature | humidity
------+----------+--------+-------------+----------
(0 rows)
  1. DROP 删除 hypertable 只需要使用 PG 命令删除基表(普通表)即可
testdb=# DROP TABLE conditions;
DROP TABLE

2.2 编辑超表 hypertable

hypertable 的修改和标准 SQL 一致,可以使用 ALTER TABLE 相关语句实现:http://www.postgres.cn/docs/12/ddl-alter.html

  1. 增删列

增加列 column 时,如果没有默认值即 NULL 时,新增操作可以很快完成;但是默认值为非空的时候,就需要花大量时间填充所有分区中每条记录新增列的值。

另外,无法对已经被压缩的 hypertable 进行增删列操作,如果要进行该操作需要先解压

testdb=# \d conditionsTable "public.conditions"Column    |           Type           | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+---------time        | timestamp with time zone |           | not null |location    | text                     |           | not null |device      | text                     |           | not null |temperature | double precision         |           |          |humidity    | double precision         |           |          |
Indexes:"conditions_time_idx" btree ("time" DESC)
Triggers:ts_insert_blocker BEFORE INSERT ON conditions FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()
Number of child tables: 1 (Use \d+ to list them.)testdb=# ALTER TABLE conditions
ADD COLUMN test_column DOUBLE PRECISION NULL;
ALTER TABLE
testdb=# \d conditionsTable "public.conditions"Column    |           Type           | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+---------time        | timestamp with time zone |           | not null |location    | text                     |           | not null |device      | text                     |           | not null |temperature | double precision         |           |          |humidity    | double precision         |           |          |test_column | double precision         |           |          |
Indexes:"conditions_time_idx" btree ("time" DESC)
Triggers:ts_insert_blocker BEFORE INSERT ON conditions FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()
Number of child tables: 1 (Use \d+ to list them.)testdb=# ALTER TABLE conditions
DROP COLUMN test_column;
ALTER TABLE
testdb=# \d conditionsTable "public.conditions"Column    |           Type           | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+---------time        | timestamp with time zone |           | not null |location    | text                     |           | not null |device      | text                     |           | not null |temperature | double precision         |           |          |humidity    | double precision         |           |          |
Indexes:"conditions_time_idx" btree ("time" DESC)
Triggers:ts_insert_blocker BEFORE INSERT ON conditions FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()
Number of child tables: 1 (Use \d+ to list them.)
  1. 重命名列或表
testdb=# \d conditionsTable "public.conditions"Column    |           Type           | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+---------time        | timestamp with time zone |           | not null |location    | text                     |           | not null |device      | text                     |           | not null |temperature | double precision         |           |          |humidity    | double precision         |           |          |test_column | double precision         |           |          |
Indexes:"conditions_time_idx" btree ("time" DESC)
Triggers:ts_insert_blocker BEFORE INSERT ON conditions FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()
Number of child tables: 1 (Use \d+ to list them.)testdb=# ALTER TABLE conditions RENAME COLUMN test_column TO ts_column;
ALTER TABLE
testdb=# ALTER TABLE conditions RENAME TO weather;
ALTER TABLE
testdb=# \d conditions
Did not find any relation named "conditions".
testdb=# \d weatherTable "public.weather"Column    |           Type           | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+---------time        | timestamp with time zone |           | not null |location    | text                     |           | not null |device      | text                     |           | not null |temperature | double precision         |           |          |humidity    | double precision         |           |          |ts_column   | double precision         |           |          |
Indexes:"conditions_time_idx" btree ("time" DESC)
Triggers:ts_insert_blocker BEFORE INSERT ON weather FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()
Number of child tables: 1 (Use \d+ to list them.)

2.3 修改 hypertable 分区间隔

  1. 普通表转化成 hypertable 时指定分区时间间隔 chunk_time_interval

如果创建 hypertable 是没有指定分区间隔,默认值是 7 天;可以通过查询 _timescaledb.catalog 查看分区间隔的当前设置

testdb=# CREATE TABLE conditions (time        TIMESTAMPTZ       NOT NULL,location    TEXT              NOT NULL,device      TEXT              NOT NULL,temperature DOUBLE PRECISION  NULL,humidity    DOUBLE PRECISION  NULL
);
CREATE TABLE
testdb=# SELECT create_hypertable('conditions', 'time');create_hypertable
-------------------------(2,public,conditions,t)
(1 row)testdb=# SELECT h.table_name, c.interval_lengthFROM _timescaledb_catalog.dimension cJOIN _timescaledb_catalog.hypertable hON h.id = c.hypertable_id;table_name | interval_length
------------+-----------------conditions |    604800000000
(1 row)

可以看到没有指定 chunk_time_interval 的 hypertable 分区间隔为 604800000000 / 1000 / 1000 / 60 / 60 / 24 = 7,interval_length 的单位为微秒(microsecond)

创建 hypertable 时我们通过 chunk_time_interval 指定分区间隔为 1 天

testdb=# DROP TABLE conditions;
DROP TABLE
testdb=# CREATE TABLE conditions (time        TIMESTAMPTZ       NOT NULL,location    TEXT              NOT NULL,device      TEXT              NOT NULL,temperature DOUBLE PRECISION  NULL,humidity    DOUBLE PRECISION  NULL
);
CREATE TABLE
testdb=# SELECT create_hypertable('conditions','time',chunk_time_interval => INTERVAL '1 day'
);create_hypertable
-------------------------(3,public,conditions,t)
(1 row)testdb=# SELECT h.table_name, c.interval_lengthFROM _timescaledb_catalog.dimension cJOIN _timescaledb_catalog.hypertable hON h.id = c.hypertable_id;table_name | interval_length
------------+-----------------conditions |     86400000000
(1 row)
  1. 通过 set_chunk_time_interval 函数修改 hypertable 分区间隔

需要注意的是修改分区时间间隔只会再新建的分区中生效,已经创建的分区不会受到影响。所以如果创建了一个很长时间的分区间隔例如 1 年,然后你想修改成一个更小的分区间隔,那这个更小间隔只会在一年后生效了,这时候只能新建一个表设置分区间隔,然后迁移数据了。

testdb=# SELECT set_chunk_time_interval('conditions', INTERVAL '12 hours');set_chunk_time_interval
-------------------------(1 row)testdb=# SELECT h.table_name, c.interval_lengthFROM _timescaledb_catalog.dimension cJOIN _timescaledb_catalog.hypertable hON h.id = c.hypertable_id;table_name | interval_length
------------+-----------------conditions |     43200000000
(1 row)

2.4 hypertable 创建索引

在一个 hypertable 中创建索引分为两步:

  1. 确定该超表的分区列有哪些,其中 time 列是所有 hypertable 表的分区列,所以创建索引必须包含该列;另外,在创建 hypertable 表时可以通过 partitioning_column 字段指定空间分区列。
  2. 创建的索引组合必须包括所有分区列,在此基础上增加其他列
  1. 创建索引

hypertable 中索引的创建仍是使用标准的 SQL 语句 CREATE INDEX / CREATE UNIQUE INDEX,例如,如下例子中在 conditions 超表的 time 和 device 列上建立索引 idx_device_time

testdb=# \d conditionsTable "public.conditions"Column    |           Type           | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+---------time        | timestamp with time zone |           | not null |location    | text                     |           | not null |device      | text                     |           | not null |temperature | double precision         |           |          |humidity    | double precision         |           |          |
Indexes:"conditions_time_idx" btree ("time" DESC)
Triggers:ts_insert_blocker BEFORE INSERT ON conditions FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()
Number of child tables: 1 (Use \d+ to list them.)testdb=# CREATE UNIQUE INDEX idx_device_time
ON conditions(device, time);
CREATE INDEX
testdb=# \d conditionsTable "public.conditions"Column    |           Type           | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+---------time        | timestamp with time zone |           | not null |location    | text                     |           | not null |device      | text                     |           | not null |temperature | double precision         |           |          |humidity    | double precision         |           |          |
Indexes:"idx_device_time" UNIQUE, btree (device, "time")"conditions_time_idx" btree ("time" DESC)
Triggers:ts_insert_blocker BEFORE INSERT ON conditions FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()
Number of child tables: 1 (Use \d+ to list them.)

idx_device_time 索引中包含了所有分区列 time,而 device 不是分区列,如果创建的索引组合不包含分区列,会抛出错误,如下 idx_device 索引仅建立在 device 列上

testdb=# CREATE UNIQUE INDEX idx_device
ON conditions(device);
ERROR:  cannot create a unique index without the column "time" (used in partitioning)
testdb=#
  1. 删除索引

hypertable 中删除索引仍是使用标准的 SQL 语句 DROP INDEX,删除 conditions 超表中的索引 idx_device_time

需要注意的是DBMS为主键约束和唯一约束自动创建的索引是无法删除的

testdb=# \d conditionsTable "public.conditions"Column    |           Type           | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+---------time        | timestamp with time zone |           | not null |location    | text                     |           | not null |device      | text                     |           | not null |temperature | double precision         |           |          |humidity    | double precision         |           |          |
Indexes:"idx_device_time" UNIQUE, btree (device, "time")"conditions_time_idx" btree ("time" DESC)
Triggers:ts_insert_blocker BEFORE INSERT ON conditions FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()
Number of child tables: 1 (Use \d+ to list them.)testdb=# DROP INDEX idx_device_time;
DROP INDEX
testdb=# \d conditionsTable "public.conditions"Column    |           Type           | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+---------time        | timestamp with time zone |           | not null |location    | text                     |           | not null |device      | text                     |           | not null |temperature | double precision         |           |          |humidity    | double precision         |           |          |
Indexes:"conditions_time_idx" btree ("time" DESC)
Triggers:ts_insert_blocker BEFORE INSERT ON conditions FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()
Number of child tables: 1 (Use \d+ to list them.)
  1. 已建索引的普通表转化为 hypertable,空间分区列 partitioning_column 必须包含在已建的索引中

例如,我们在普通表 basic_table 中已经在 device_id 和 time 列上建立了索引 idx_deviceid_time,那么创建以该表为基表的 hypertable 的分区列需要包含在索引列中,即分区列仅能为 time 与 device_id 的组合。

下例中,将已经创建好索引的 basic_table 表转化为仅以 time 为分区列的 hypertable

testdb=# CREATE TABLE basic_table(time TIMESTAMPTZ,user_id BIGINT,device_id BIGINT,value FLOAT
);
CREATE TABLE
testdb=# CREATE UNIQUE INDEX idx_deviceid_timeON basic_table(device_id, time);
CREATE INDEX
testdb=# \d basic_tableTable "public.basic_table"Column   |           Type           | Collation | Nullable | Default
-----------+--------------------------+-----------+----------+---------time      | timestamp with time zone |           |          |user_id   | bigint                   |           |          |device_id | bigint                   |           |          |value     | double precision         |           |          |
Indexes:"idx_deviceid_time" UNIQUE, btree (device_id, "time")testdb=# SELECT * from create_hypertable('basic_table', 'time');
NOTICE:  adding not-null constraint to column "time"
DETAIL:  Time dimensions cannot have NULL values.hypertable_id | schema_name | table_name  | created
---------------+-------------+-------------+---------4 | public      | basic_table | t
(1 row)testdb=# \d basic_tableTable "public.basic_table"Column   |           Type           | Collation | Nullable | Default
-----------+--------------------------+-----------+----------+---------time      | timestamp with time zone |           | not null |user_id   | bigint                   |           |          |device_id | bigint                   |           |          |value     | double precision         |           |          |
Indexes:"idx_deviceid_time" UNIQUE, btree (device_id, "time")"basic_table_time_idx" btree ("time" DESC)
Triggers:ts_insert_blocker BEFORE INSERT ON basic_table FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()

也可以将已经创建好索引的 basic_table 表转化为以 time 和 device_id 为分区列的 hypertable

testdb=# SELECT * FROM create_hypertable('basic_table','time',partitioning_column => 'device_id',number_partitions => 4
);
NOTICE:  adding not-null constraint to column "time"
DETAIL:  Time dimensions cannot have NULL values.hypertable_id | schema_name | table_name  | created
---------------+-------------+-------------+---------5 | public      | basic_table | t
(1 row)testdb=# \d basic_tableTable "public.basic_table"Column   |           Type           | Collation | Nullable | Default
-----------+--------------------------+-----------+----------+---------time      | timestamp with time zone |           | not null |user_id   | bigint                   |           |          |device_id | bigint                   |           |          |value     | double precision         |           |          |
Indexes:"idx_deviceid_time" UNIQUE, btree (device_id, "time")"basic_table_time_idx" btree ("time" DESC)
Triggers:ts_insert_blocker BEFORE INSERT ON basic_table FOR EACH ROW EXECUTE FUNCTION _timescaledb_internal.insert_blocker()

但是,我们无法将不在索引组合中的 user_id 作为创建 hypertable 时的分区列

要解决这个问题,要确保在转化为超表之前建立的所有索引都要包含 hypertable 的分区列,所以将已存在的索引中加入 user_id 即可(重建索引可以重建一个索引,然后删除老的索引,避免使用 reindex 重建索引,因为该过程是阻塞的,一般大表不建议使用这个命令 )

testdb=# \d basic_tableTable "public.basic_table"Column   |           Type           | Collation | Nullable | Default
-----------+--------------------------+-----------+----------+---------time      | timestamp with time zone |           |          |user_id   | bigint                   |           |          |device_id | bigint                   |           |          |value     | double precision         |           |          |
Indexes:"idx_deviceid_time" UNIQUE, btree (device_id, "time")testdb=# SELECT * FROM create_hypertable('basic_table','time',partitioning_column => 'user_id',number_partitions => 4
);
NOTICE:  adding not-null constraint to column "time"
DETAIL:  Time dimensions cannot have NULL values.
ERROR:  cannot create a unique index without the column "user_id" (used in partitioning)
testdb=# DROP INDEX idx_deviceid_time;
DROP INDEX
testdb=# CREATE UNIQUE INDEX idx_userid_deviceid_timeON basic_table(user_id, device_id, time);
CREATE INDEX
testdb=# \d basic_tableTable "public.basic_table"Column   |           Type           | Collation | Nullable | Default
-----------+--------------------------+-----------+----------+---------time      | timestamp with time zone |           |          |user_id   | bigint                   |           |          |device_id | bigint                   |           |          |value     | double precision         |           |          |
Indexes:"idx_userid_deviceid_time" UNIQUE, btree (user_id, device_id, "time")testdb=# SELECT * FROM create_hypertable('basic_table','time',partitioning_column => 'user_id',number_partitions => 4
);
NOTICE:  adding not-null constraint to column "time"
DETAIL:  Time dimensions cannot have NULL values.hypertable_id | schema_name | table_name  | created
---------------+-------------+-------------+---------12 | public      | basic_table | t
(1 row)

如果文章对你有帮助,欢迎一键三连 👍 ⭐️ 💬 。如果还能够点击关注,那真的是对我最大的鼓励 🔥 🔥 🔥 。


参考资料

https://docs.timescale.com/self-hosted/latest/install/installation-source/
https://docs.timescale.com/use-timescale/latest/hypertables/create/
PolarDB 开源版 使用TimescaleDB 实现时序数据高速写入、压缩、实时聚合计算、自动老化等-阿里云开发者社区
https://zhuanlan.zhihu.com/p/57120174

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/78177.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2023/9/13 -- C++/QT

作业&#xff1a; 1> 将之前定义的栈类和队列类都实现成模板类 栈&#xff1a; #include <iostream> #define MAX 40 using namespace std;template <typename T> class Stack{ private:T *data;int top; public:Stack();~Stack();Stack(const Stack &ot…

TouchGFX之缓存位图

位图缓存是专用RAM缓冲区&#xff0c;应用可将位图保存&#xff08;或缓存&#xff09;在其中。 如果缓存了位图&#xff0c;在绘制位图时&#xff0c;TouchGFX将自动使用RAM缓存作为像素来源。位图缓存在许多情况下十分有用。 从RAM读取数据通常比从闪存读取要快&#xff08;特…

Linux下Minio分布式存储安装配置(图文详细)

文章目录 Linux下Minio分布式存储安装配置(图文详细)1 资源准备1.1 创建存储目录1.2 获取Minio Server资源1.3 获取Minio Client资源 2 Minio Server安装配置2.1 切换目录2.2 后台启动2.3 查看进程2.4 控制台测试 3 Minio Client安装配置3.1 切换目录3.2 移动mc脚本3.2 运行mc命…

Vue3后台管理系统Element-plus_侧边栏制作_无限递归

在home.view中添加代码 <template><div><div class"common-layout"><el-container><el-header class"common-header flex-float"><div class"flex"><img class"logo" src"../assets/logo…

【Redis】Redis实现分布式锁

【Redis】Redis常见面试题&#xff08;1&#xff09; 文章目录 【Redis】Redis常见面试题&#xff08;1&#xff09;1. 为什么要用分布式锁2. Redis如何实现分布式锁3. Redis接受多个请求模拟演示4. 使用Redis实现分布式锁会存在什么问题4.1 一个锁被长时间占用4.2 锁误删 【Re…

vue2+element-ui批量导入方法并判断上传的文件是否为xls或xlsx

业务需求: 代码结构: <el-dialogtitle"批量导入":close-on-click-modal"true"close"close()":visible"true"width"35%":center"true"><div class"el-dialog-div"><!-- 头部区域布局 -…

【基本数据结构 四】线性数据结构:队列

学习了栈后,再来看看第四种线性表结构,也就是队列,队列和栈一样也是一种受限的线性表结构,和栈后进先出的操作方式不同的是,队列是FIFO的结构,也就是先进先出的操作方式。 队列的定义 队列这个概念非常好理解。可以把它想象成排队买票,先来的先买,后来的人只能站末尾…

软考知识汇总--结构化开发方法

文章目录 1 结构化开发2 耦合3 内聚4 设计原则5 系统文档6 数据流图6.1 数据流图的基本图形元素 7 数据字典 1 结构化开发 结构化方法总的指导思想是自顶向下、逐层分解&#xff0c;它的基本原则是功能的分解与抽象。它是软件工程中最早出现的开发方法&#xff0c;特别适合于数…

「C++程序设计 (面向对象进阶)」学习笔记・二

0、引言 本专栏的系列文章是在学习 北京邮电大学 崔毅东 老师的《C程序设计 (面向对象进阶)》课程过程中整理的。欢迎前往专栏了解更多相关内容~ &#x1f600; 有关于现代 C 的基本介绍&#xff0c;请前往《现代C基本介绍》&#xff01; &#x1f514; 先决条件 本专栏的系列…

定时器+BOM

9.定时器BOM 1.定时器 **概念:**重复执行一个函数 1.1setInterval() setInterval(“代码/函数”,时间,参数),返回定时器的序列号,默认从1开始 clearInterval(序列号)清除定时 <button class"start">开启定时器</button><button class"close…

通过Power Platform自定义D365 CE 业务需求 - 3. 使用Microsoft Power应用程序

Microsoft Power Apps是一个用于开发应用程序的无代码、无代码平台。Power应用程序可以在Dataverse之上配置为数据库。尽管您可以连接Salesforce、OneDrive、Dropbox等多种云源,但Dataverse也可以用作内部数据库来构建应用程序,并通过连接器连接其他数据源进行集成。 Power应…

Java开发之Redis核心内容【面试篇 完结版】

文章目录 前言一、redis使用场景1. 知识分布2. 缓存穿透① 问题引入② 举例说明③ 解决方案④ 实战面试 3. 缓存击穿① 问题引入② 举例说明③ 解决方案④ 实战面试 4. 缓存雪崩① 问题引入② 举例说明③ 解决方案④ 实战面试 5. 缓存-双写一致性① 问题引入② 举例说明③ 解决…

内存管理机制

aCoral内存管理机制 aCoral内存管理机制在伙伴系统基础上&#xff0c;采用了位图法方式提高内存分配和回收速度的确定性&#xff0c;更能满足系统实时性的需求。 aCoral内存管理机制分为两级&#xff0c;上一级采用改进的伙伴系统&#xff0c;负责确定要分配的内存的大小&…

数据分析综述

⭐️⭐️⭐️⭐️⭐️欢迎来到我的博客⭐️⭐️⭐️⭐️⭐️ &#x1f434;作者&#xff1a;秋无之地 &#x1f434;简介&#xff1a;CSDN爬虫、后端、大数据领域创作者。目前从事python爬虫、后端和大数据等相关工作&#xff0c;主要擅长领域有&#xff1a;爬虫、后端、大数据…

C#类与类库调用注意事项

类 创建一个类文件&#xff0c;myfunction.cs //静态类&#xff1a;直接引用、无需实例化 static public int jiafa(int V) //普通类&#xff1a;引用时需要实例化 public int jiafa(int V)using System; using System.Collections.Generic; using System.Diagnostics; using …

ChatGPT追祖寻宗:GPT-2论文要点解读

论文地址&#xff1a;Language Models are Unsupervised Multitask Learners 上篇&#xff1a;GPT-1论文要点解读 在上篇&#xff1a;GPT-1论文要点解读中我们介绍了GPT1论文中的相关要点内容&#xff0c;其实自GPT模型诞生以来&#xff0c;其核心模型架构基本没有太大的改变&a…

Vue中extend基本用法

1.Vue.extend(options) 参数: {Object} options用法&#xff1a; 使用基础Vue构造器&#xff0c;创建一个"子类"。参数是一个包含组件选项的对象。 data选项是特例&#xff0c;需要注意&#xff0c;在Vue.extend()中它必须是函数。 <html><head><tit…

读高性能MySQL(第4版)笔记08_创建高性能索引(上)

1. 索引 1.1. 键&#xff08;key&#xff09; 1.2. 存储引擎用于快速找到记录的一种数据结构 1.3. 当表中的数据量越来越大时&#xff0c;索引对性能的影响愈发重要 1.4. 在数据量较小且负载较低时&#xff0c;缺少合适的索引对性能的影响可能还不明显 1.5. 索引优化是对查…

C#__线程池的简单介绍和使用

/*线程池原理&#xff1a;&#xff08;有备无患的默认备用后台线程&#xff09;特点&#xff1a;线程提前建好在线程池;只能用于运行时间较短的线程。*/class Program{static void Main(string[] args){for (int i 0; i < 10; i){ThreadPool.QueueUserWorkItem(Download); …

【Redis】Redis作为缓存

【Redis】Redis常见面试题&#xff08;2&#xff09; 文章目录 【Redis】Redis常见面试题&#xff08;2&#xff09;1. 缓存2. Redis作为缓存2.1 缓存雪崩2.2 缓存穿透2.3 缓存击穿2.4 缓存雪崩、缓存穿透、缓存击穿的区别2.5 缓存预热2.6 如何保证缓存和MySQL双写一致 【Redis…