PostgreSQL 自动分区分表维护管理插件 pathman 基础使用

官方地址:https://github.com/postgrespr...
关于pathman的原理和优化问题,请移步至https://yq.aliyun.com/article...

  • 检查环境变量
    如果直接执行psql命令提示command not found则执行下面的命令设置环境变量

    root@host# PATH=$PATH:$HOME/bin:/usr/local/pgsql/bin # 就是postgresql的安装路径
    root@host# export PATH

    主要是PG_CONFIG

  • 安装

    root@host# tar xf pg_pathman.tar.gz
    root@host# cd pg_pathman
    root@host# make USE_PGXS=1
    root@host# make install
  • 安装插件到数据库

    # psql -U 用户名
         -h 主机localhost
         -d 数据库名称
         -p 端口5432
         -c "create extension pg_pathman"
  • 创建主表

    # psql -U 用户名
         -h 主机localhost
         -d 数据库名称
         -p 端口5432
         -c "create table test (id serial8 primary key, area_id bigint not null, name varchar(100) not null, age integer not null default 0)"

    创建一个地区表,area_id为地区id

  • 创建分区

    • 创建hash分区

      # psql -U 用户名
           -h 主机localhost
           -d 数据库名称
           -p 端口5432
           -c "select create_hash_partitions(test,'area_id',10,false)"

      参数解析:create_hash_partitions(表名,'分区字段',分几个区,是否立即开始转移数据)

    • 创建range分区

      # psql -U 用户名
           -h 主机localhost
           -d 数据库名称
           -p 端口5432
           -c "select create_range_partitions(test,'age',0,100,1,false)"

      参数解析:select create_range_partitions(表名,分区字段,从几开始,到几结束,数据间隔,每间隔X创建一个表,是否立即迁移数据)
      range分区还有一种方法按照时间比如:

      select create_range_partitions(表名,分区字段,
          从什么时间开始如'YYYY-mm-dd HH:ii:ss'::timestamp,
          interval '1 month',
          总共创建几个表,
          是否立即迁移数据
      )
同一个表hash和range只能创建一个规则的分区

分区命令执行完毕后能立刻看到已经创建完成了N个子表,但是由于刚才设置是否立即迁移数据都是false,所以还需要执行select partition_table_concurrently(表名,每次处理几条数据,失败尝试等待秒数)开始迁移数据

迁移完成后,执行select count(*) from only test可以看到已经没有任何数据了(注意only)

 count 
-------
 0
(1 row)

使用SQLselect * from test where area_id = 1 order by id asc limit 10数据库会自动的根据area_id从某一个分片中读取数据。
使用SQLselect * from test where age > 10 order by id asc limit 10数据库会自动的根据age从某几个片中读取数据。

更加详细的请参考 德哥文章:https://yq.aliyun.com/article...

你可能感兴趣的:(postgresql)