saf*_*far 5 postgresql partitioning database-partitioning
我想按以前未知的值对 Postgres 中的表进行分区。在我的场景中,该值将是 device_id,它是一个字符串。
这是目前的情况:
表 'device_data' - 存储从设备发送的传感器数据,由 DDL 定义:
CREATE TABLE warehouse.device_data (
id INTEGER PRIMARY KEY NOT NULL DEFAULT nextval('device_data_id_seq'::regclass),
device_id TEXT NOT NULL,
device_data BYTEA NOT NULL,
-- contains additional fields which are omitted for brevity
received_at TIMESTAMP WITHOUT TIME ZONE DEFAULT now()
);
Run Code Online (Sandbox Code Playgroud)
表目前拥有数百万条记录,查询需要花费大量时间。大多数查询都包含WHERE device_id='something'子句。
我想到的解决方案是为每个device_id.
Postgres 是否可以为每个创建表分区device_id?
我浏览了 Postgres 文档和我发现的几个示例,但它们都使用固定边界来创建分区。我的解决方案需要:
device_id首次遇到new 时动态创建新的表分区device_id已知并且该分区device_id已经存在我希望使用表分区来完成这项工作,因为它允许跨多个device_ids进行查询。
I like the idea of dynamic partitioning. I do not know though how it will affect the performance as I have never used it.
Change the type of id to int default 0 and manually create the sequence to avoid multiple nextval() calls on a single insert:
create table device_data (
id int primary key default 0,
device_id text not null,
device_data text not null, -- changed for tests
received_at timestamp without time zone default now()
);
create sequence device_data_seq owned by device_data.id;
Run Code Online (Sandbox Code Playgroud)
Use dynamic sql in the trigger function:
create or replace function before_insert_on_device_data()
returns trigger language plpgsql as $$
begin
execute format(
$f$
create table if not exists %I (
check (device_id = %L)
) inherits (device_data)
$f$,
concat('device_data_', new.device_id),
new.device_id);
execute format(
$f$
insert into %I
values (nextval('device_data_seq'), %L, %L, default)
$f$,
concat('device_data_', new.device_id),
new.device_id,
new.device_data);
return null;
end $$;
create trigger before_insert_on_device_data
before insert on device_data
for each row execute procedure before_insert_on_device_data();
Run Code Online (Sandbox Code Playgroud)
Test:
insert into device_data (device_id, device_data) values
('first', 'data 1'),
('second', 'data 1'),
('first', 'data 2'),
('second', 'data 2');
select * from device_data_first;
id | device_id | device_data | received_at
----+-----------+-------------+----------------------------
1 | first | data 1 | 2016-10-18 19:50:40.179955
3 | first | data 2 | 2016-10-18 19:50:40.179955
(2 rows)
select * from device_data_second;
id | device_id | device_data | received_at
----+-----------+-------------+----------------------------
2 | second | data 1 | 2016-10-18 19:50:40.179955
4 | second | data 2 | 2016-10-18 19:50:40.179955
(2 rows)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3814 次 |
| 最近记录: |