分区表的优势:
降低大表管理成本和某些场景下的性能提升。
pg_pathman的安装
参考:https://www.jianshu.com/p/7a8737250456
我采用的是源码安装
1.克隆源码 git clone https://github.com/postgrespro/pg_pathman
2.安装 make install USE_PGXS=1
这一步可能会报错:
不要紧,把PostgreSQL的可执行文件的目录加到PATH里,我之前已经加过了,source ./bash_profile文件一下就可以了。
3.配置postgresql.conf文件
把 shared_preload_libraries参数的注释去掉
shared_preload_libraries=‘pg_pathman’
4.重启数据库,create extension pg_pathman;
用\dx 元命令可以查看当前数据库的扩展:
管理
创建分区表
postgres=# create table test_range_partition(id serial,crt_time timestamp not null,level int,info text);
CREATE TABLE
创建索引:
postgres=# create index crt_index on test_range_partition(crt_time);
CREATE INDEX
插入数据:
postgres=# insert into test_range_partition (crt_time,level,info) select g,random()*6,
md5(g::text) from generate_series('2019-01-01'::date,'2019-12-31'::date,'1 minute') as g;
INSERT 0 52416
创建分区
postgres=# select create_range_partitions('test_range_partition','crt_time','2019-01-01'::date,'1 day'::interval,
postgres(# null,false);
create_range_partitions
-------------------------
365
(1 row)
注意:分区字段要有not null 约束;
统计主表数据量(分区但数据未迁移)
postgres=# select count(*) from test_range_partition;
count
--------
524161
(1 row)
2.创建非阻塞分区
3.创建hash分区
创建原始表
postgres=# create table partition_hash_test(id int primary key,name text,code bigint);
CREATE TABLE
(1 row)
插入数据
postgres=# insert into partition_hash_test select g,md5(g::text),random()*100000 from generate_series(1,100000) as g;
INSERT 0 100000
创建hash分区,并迁移数据
postgres=# select create_hash_partitions('partition_hash_test','id',100);
create_hash_partitions
------------------------
100
查看数据: