5.11.2. Declarative Partitioning
5.11.2. Declarative Partitioning
5.11.2.声明分区
PostgreSQL offers a way to specify how to divide a table into pieces called partitions. The table that is divided is referred to as a partitioned table. The specification consists of the partitioning method and a list of columns or expressions to be used as the partition key.
PostgreSQL提供将表进行分区的方式。被分割的表称为分区表。分区声明由分区方式及分区键(一组列或者表达式)组成。
All rows inserted into a partitioned table will be routed to one of the partitions based on the value of the partition key. Each partition has a subset of the data defined by its partition bounds. The currently supported partitioning methods are range, list, and hash.
所有插入分区表的行将根据分区键被路由到相应的分区中。每个分区都有一个由其分区范围定义的数据子集。当前支持的分区方法有范围,列表和哈希分区。
Partitions may themselves be defined as partitioned tables, using what is called sub-partitioning. Partitions may have their own indexes, constraints and default values, distinct from those of other partitions.See CREATE TABLE for more details on creating partitioned tables and partitions.
子分区也可定义为分区表,即为子分区。分区可以具有与其他分区不同的索引、约束和默认值。有关创建分区表及分区的更多信息,参见命令 CREATE TABLE。
It is not possible to turn a regular table into a partitioned table or vice versa. However, it is possible to add a regular or partitioned table containing data as a partition of a partitioned table, or remove a partition from a partitioned table turning it into a standalone table; see ALTER TABLE to learn more about the ATTACH PARTITION and DETACH PARTITION sub-commands.
将普通表转为分区表是不可以的,反之亦然。然而,将包含数据的普通表或分区表附加到分区表中作为一个分区,或者将分区表的一个分区移除出来作为普通表却是可以的;请参阅ALTER TABLE,以了解有关ATTACH PARTITION和DETACH PARTITION子命令的更多信息。
Individual partitions are linked to the partitioned table with inheritance behind-the-scenes; however, it is not possible to use some of the generic features of inheritance (discussed below) with declaratively partitioned tables or their partitions. For example, a partition cannot have any parents other than the partitioned table it is a partition of, nor can a regular table inherit from a partitioned table making the latter its parent. That means partitioned tables and their partitions do not participate in inheritance with regular tables. Since a partition hierarchy consisting of the partitioned table and its partitions is still an inheritance hierarchy, all the normal rules of inheritance apply as described in Section 5.9 with some exceptions, most notably:
各个分区通过后台继承链接到分区表。但是,无法对分区表或其分区使用继承的某些通用功能(如下所述)。例如,一个分区除了它所属于的分区表,不能有其他父表,常规表也不可让分区表作为其父表并从其继承。也就是说,分区表及其分区不参与常规表的继承。由于由分区表及其分区组成的分区层次结构仍然是继承层次结构,因此所有正常的继承规则都适用于第5.10节中所述,但有一些例外,最值得注意的是:
• Both CHECK and NOT NULL constraints of a partitioned table are always inherited by all its partitions. CHECK constraints that are marked NO INHERIT are not allowed to be created on partitioned tables.
•分区表中的检查和非空约束,均被其分区所继承。在分区表中不能创建指定NO INHERIT的检查约束。
• Using ONLY to add or drop a constraint on only the partitioned table is supported as long as there are no partitions. Once partitions exist, using ONLY will result in an error as adding or dropping constraints on only the partitioned table, when partitions exist, is not supported. Instead, constraints on the partitions themselves can be added and (if they are not present in the parent table) dropped.
• 仅在没有分区的情况下,才支持分区表上使用ONLY添加或删除约束。一旦存在分区,使用ONLY在分区表添加或删除索引将报错;实际上,当分区存在,此行为不受支持。相反,可以添加对分区本身的约束,并且可以删除(如果它们不在父表中)。
• As a partitioned table does not have any data directly, attempts to use TRUNCATE ONLY on a partitioned table will always return an error.
•因为分区表并不直接存储数据,所以对分区表执行TRUNCATE ONLY总会返回错误。
• Partitions cannot have columns that are not present in the parent. It is not possible to specify columns when creating partitions with CREATE TABLE, nor is it possible to add columns to partitions after-the-fact using ALTER TABLE. Tables may be added as a partition with ALTER TABLE ... ATTACH PARTITION only if their columns exactly match the parent, including any oid column.
•分区中不能具有父表中不存在的表。 使用CREATE TABLE创建分区时无法指定列,也无法在事后使用ALTER TABLE将列添加到分区中。仅当表的列与父表(包括任何oid列)完全匹配时,才可以使用ALTER TABLE ... ATTACH PARTITION将其添加为分区。
• You cannot drop the NOT NULL constraint on a partition's column if the constraint is present in the parent table.
•如果父表定义了非空约束,那么不能在分区中将其删除。
Partitions can also be foreign tables, although they have some limitations that normal tables do not; see CREATE FOREIGN TABLE for more information.
分区也可以是外表,虽然它们会有比普通表更多的限制;更多信息请参见 CREATE FOREIGN TABLE。
Updating the partition key of a row might cause it to be moved into a different partition where this row satisfies the partition bounds.
更新分区键可能会导致其移动到满足分区范围的分区中。
5.11.2.1. Example
5.11.2.1.示例
Suppose we are constructing a database for a large ice cream company. The company measures peak temperatures every day as well as ice cream sales in each region. Conceptually, we want a table like:
假设,我们在为一个大型冰淇淋公司设计数据库。 该公司每天测量峰值温度以及每个地区的冰淇淋销售量。 从概念上讲,我们想要一个像这样的表:
CREATE TABLE measurement (
city_id int not null,
logdate date not null,
peaktemp int,
unitsales int
);
We know that most queries will access just the last week's, month's or quarter's data, since the main use of this table will be to prepare online reports for management. To reduce the amount of old data that needs to be stored, we decide to only keep the most recent 3 years worth of data. At the beginning of each month we will remove the oldest month's data. In this situation we can use partitioning to help us meet all of our different requirements for the measurements table.
我们知道大多数查询将仅访问上周,月或季度的数据,因为此表的主要用途是为管理层准备在线报告。 为了减少需要存储的旧数据量,我们决定只保留最近3年的数据。 在每个月初,我们将删除最旧月份的数据。 在这种情况下,我们可以使用分区来帮助我们满足measurement表的所有不同需求。
To use declarative partitioning in this case, use the following steps:
这种情况下声明分区,请遵从以下步骤:
1. Create measurement table as a partitioned table by specifying the PARTITION BY clause,which includes the partitioning method (RANGE in this case) and the list of column(s) to use as the partition key.
1.使用PARTITION BY子句创建分区表measurement,并指定分区方式为RANGE,以及指定作为分区键的列。
CREATE TABLE measurement (
city_id int not null,
logdate date not null,
peaktemp int,
unitsales int
) PARTITION BY RANGE (logdate);
You may decide to use multiple columns in the partition key for range partitioning, if desired.Of course, this will often result in a larger number of partitions, each of which is individually smaller. On the other hand, using fewer columns may lead to a coarser-grained partitioning criteria with smaller number of partitions. A query accessing the partitioned table will have to scan fewer partitions if the conditions involve some or all of these columns. For example, consider a table range partitioned using columns lastname and firstname (in that order) as the partition key.
如果需要,您可以使用多个列作为分区键进行范围分区,当然,这通常会导致分区数量增加,每个分区会较小。 另一方面,使用较少的列可能会因划分标准的粗糙而导致分区数较少。 如果条件涉及这些列中的某些或全部,则访问分区表的查询将必须扫描较少的分区。 例如,假设一张表使用列lastname和firstname作为分区键进行范围分区。
2. Create partitions. Each partition's definition must specify the bounds that correspond to the partitioning method and partition key of the parent. Note that specifying bounds such that the new partition's values will overlap with those in one or more existing partitions will cause an error. Inserting data into the parent table that does not map to one of the existing partitions will cause an error; an appropriate partition must be added manually.
2.创建分区。每个分区必须指定与父表中分区方式和分区键相对应的界限。注意,如果新分区的界限与现有分区重叠,则会报错。插入的数据如果未映射到现有分区,则会报错;此情况,必须手动添加一个合适的分区。
Partitions thus created are in every way normal PostgreSQL tables (or, possibly, foreign tables). It is possible to specify a tablespace and storage parameters for each partition separately.
这样创建的分区在所有方面与普通的PostgreSQL表(或外部表)一样。 可以分别为每个分区指定表空间和存储参数。
It is not necessary to create table constraints describing partition boundary condition for partitions.Instead, partition constraints are generated implicitly from the partition bound specification whenever there is need to refer to them.
不必为分区创建描述分区边界条件的表约束,而是会在需要引用分区约束规范时隐式生成分区约束。
CREATE TABLE measurement_y2006m02 PARTITION OF measurement
FOR VALUES FROM ('2006-02-01') TO ('2006-03-01');
CREATE TABLE measurement_y2006m03 PARTITION OF measurement
FOR VALUES FROM ('2006-03-01') TO ('2006-04-01');
...
CREATE TABLE measurement_y2007m11 PARTITION OF measurement
FOR VALUES FROM ('2007-11-01') TO ('2007-12-01');
CREATE TABLE measurement_y2007m12 PARTITION OF measurement
FOR VALUES FROM ('2007-12-01') TO ('2008-01-01')
TABLESPACE fasttablespace;
CREATE TABLE measurement_y2008m01 PARTITION OF measurement
FOR VALUES FROM ('2008-01-01') TO ('2008-02-01')
WITH (parallel_workers = 4)
TABLESPACE fasttablespace;
To implement sub-partitioning, specify the PARTITION BY clause in the commands used to create individual partitions, for example:
可以在创建单独分区的时候,使用PARTITION BY子句实现子分区,例如:
CREATE TABLE measurement_y2006m02 PARTITION OF measurement
FOR VALUES FROM ('2006-02-01') TO ('2006-03-01')
PARTITION BY RANGE (peaktemp);
After creating partitions of measurement_y2006m02, any data inserted into measurement that is mapped to measurement_y2006m02 (or data that is directly inserted into measurement_y2006m02, provided it satisfies its partition constraint) will be further redirected to one of its partitions based on the peaktemp column. The partition key specified may overlap with the parent's partition key, although care should be taken when specifying the bounds of a sub-partition such that the set of data it accepts constitutes a subset of what the partition's own bounds allows;the system does not try to check whether that's really the case.
在创建分区measurement_y2006m02后,插入表measurement中符合分区measurement_y2006m02条件的数据(或者直接插入 measurement_y2006m02中符合其分区边界的数据)会再次基于列peaktemp进行分区。指定的子分区键可能与父分区的分区键重叠,且在指定子分区的边界时应格外小心,需使其接受的数据集为该分区自身边界所允许的子集;创建时系统并不会尝试检查是否确实如此。
3. Create an index on the key column(s), as well as any other indexes you might want, on the partitioned table. (The key index is not strictly necessary, but in most scenarios it is helpful.) This automatically creates one index on each partition, and any partitions you create or attach later will also contain the index.
3.在分区表的分区键列上或其他需要的列上创建索引。(虽然在键上创建索引并不是必须的,但往往是有用的。)这会自动的在所有分区上创建索引,而且后续创建或者附加的分区也会包含此索引。
CREATE INDEX ON measurement (logdate);
4. Ensure that the enable_partition_pruning configuration parameter is not disabled in postgresql.conf. If it is, queries will not be optimized as desired.
4.确保postgresql.conf中的enable_partition_pruning配置参数启用。如果未启用,则查询不会被优化。
In the above example we would be creating a new partition each month, so it might be wise to write a script that generates the required DDL automatically.
上例中,需要每月创建一个分区,所以可以考虑写个脚本自动生成所需的DDL添加分区语句。
5.11.2.2. Partition Maintenance
5.11.2.2.分区维护
Normally the set of partitions established when initially defining the table are not intended to remain static. It is common to want to remove old partitions of data and periodically add new partitions for new data. One of the most important advantages of partitioning is precisely that it allows this otherwise painful task to be executed nearly instantaneously by manipulating the partition structure, rather than physically moving large amounts of data around.
通常,最初定义表时建立的分区集并不会是静态的。通常希望删除数据的旧分区,并定期为新数据添加新分区。分区的最重要优点之一就是,它允许通过操纵分区结构而不是物理地移动大量数据,来几乎立即执行此原本很痛苦的任务。
The simplest option for removing old data is to drop the partition that is no longer necessary:
删除旧数据最简单的选择是直接删掉不需要的分区:
DROP TABLE measurement_y2006m02;
This can very quickly delete millions of records because it doesn't have to individually delete every record. Note however that the above command requires taking an ACCESS EXCLUSIVE lock on the parent table.
因为此操作无需一行行删除数据,所以可以很快的删掉百万级记录。但请注意,以上命令会在父表上加ACCESS EXCLUSIVE锁。
Another option that is often preferable is to remove the partition from the partitioned table but retain access to it as a table in its own right:
另一个更优选择是仅将该分区从分区表中分离,但仍作为表保留:
ALTER TABLE measurement DETACH PARTITION measurement_y2006m02;
This allows further operations to be performed on the data before it is dropped. For example, this is often a useful time to back up the data using COPY, pg_dump, or similar tools. It might also be a useful time to aggregate data into smaller formats, perform other data manipulations, or run reports.
这使得在将数据删除之前可以做更深入的操作。例如,此时正是备份此数据(使用COPY,pg_dump或类似的工具)的恰当时机。 这也是对数据进行分析,执行其他数据操作或运行报告的恰当时间。
Similarly we can add a new partition to handle new data. We can create an empty partition in the partitioned table just as the original partitions were created above:
类似的,我们也可以添加新的分区以保存新的数据。我们可以像上面创建原始分区那样为分区表创建一个空的分区:
CREATE TABLE measurement_y2008m02 PARTITION OF measurement
FOR VALUES FROM ('2008-02-01') TO ('2008-03-01')
TABLESPACE fasttablespace;
As an alternative, it is sometimes more convenient to create the new table outside the partition structure, and make it a proper partition later. This allows the data to be loaded, checked, and transformed prior to it appearing in the partitioned table:
作为替代方案,有时在分区结构之外创建新表,并稍后使其成为合适的分区会更为方便。 这允许在数据出现在分区表中之前对其进行加载,检查和转换:
CREATE TABLE measurement_y2008m02
(LIKE measurement INCLUDING DEFAULTS INCLUDING CONSTRAINTS)
TABLESPACE fasttablespace;
ALTER TABLE measurement_y2008m02 ADD CONSTRAINT y2008m02
CHECK ( logdate >= DATE '2008-02-01' AND logdate < DATE
'2008-03-01' );
\copy measurement_y2008m02 from 'measurement_y2008m02'
-- possibly some other data preparation work
ALTER TABLE measurement ATTACH PARTITION measurement_y2008m02
FOR VALUES FROM ('2008-02-01') TO ('2008-03-01' );
Before running the ATTACH PARTITION command, it is recommended to create a CHECK constraint on the table to be attached describing the desired partition constraint. That way, the system will be able to skip the scan to validate the implicit partition constraint. Without such a constraint, the table will be scanned to validate the partition constraint while holding an ACCESS EXCLUSIVE lock on the parent table. One may then drop the constraint after ATTACH PARTITION is finished, because it is no longer necessary.
在执行ATTACH PARTITION命令之前,建议在要附加的表上创建CHECK约束,以满足所需的分区约束。这样,系统将能够跳过验证隐式分区约束的扫描。没有这种约束,将扫描表行以验证分区约束,同时会在父表上加ACCESS EXCLUSIVE锁。 然后,由于不再需要该约束,因此可以在ATTACH PARTITION完成后删除该约束。
如前所述,可以在分区表上创建索引,索引会自动创建到其分区上(含后来添加的分区)。不过限制是,不能使用CONCURRENTLY选项在分区表创建索引。可通过如下方式克服创建索引时的锁定时间问题:首先在分区表上使用CREATE INDEX ON ONLY创建索引,该索引此时为不可用状态,且不会自动在分区上创建索引;然后可以使用CONCURRENTLY选项在各分区创建索引;最后使用ALTER INDEX ... ATTACH PARTITION命令将分区上的索引附加到主表上的索引。一旦分区上的索引都附加到了主表索引上,主表索引会自动变为可用状态。示例:
CREATE INDEX measurement_usls_idx ON ONLY measurement (unitsales);
CREATE INDEX measurement_usls_200602_idx
ON measurement_y2006m02 (unitsales);
ALTER INDEX measurement_usls_idx
ATTACH PARTITION measurement_usls_200602_idx;
...
该方法也可以用在主键及唯一约束上(创建约束时自动创建的索引)。示例:
ALTER TABLE ONLY measurement ADD UNIQUE (city_id, logdate);
ALTER TABLE measurement_y2006m02 ADD UNIQUE (city_id, logdate);
ALTER INDEX measurement_city_id_logdate_key
ATTACH PARTITION measurement_y2006m02_city_id_logdate_key;
...
5.11.2.3. Limitations
5.11.2.3.限制
The following limitations apply to partitioned tables:
分区表有以下限制:
• There is no way to create an exclusion constraint spanning all partitions; it is only possible to constrain each leaf partition individually.
•无法为所有分区创建排他约束;只可以为每个分区单独创建。
唯一约束必须包含所有分区键列。
BEFORE ROW触发器不能决定新行插入到哪个分区。
• Mixing temporary and permanent relations in the same partition tree is not allowed. Hence, if the partitioned table is permanent, so must be its partitions and likewise if the partitioned table is temporary.When using temporary relations, all members of the partition tree have to be from the same session.
•同一分区树中不允许同时存在临时表和普通表。因此,分区表及其分区,临时还是永久,属性要相同。如果使用临时表,那么必须使用同一会话创建分区表及其所有分区。