# CLUSTER
CLUSTER — cluster a table according to an index
# Synopsis
CLUSTER [VERBOSE] table_name [ USING index_name ]
CLUSTER ( option [, ...] ) table_name [ USING index_name ]
CLUSTER [VERBOSE]
where option can be one of:
VERBOSE [ boolean ]
# Description
CLUSTER
instructs PostgreSQL to cluster the table specified by*table_name
based on the index specified byindex_name
. The index must already have been defined ontable_name
*.
When a table is clustered, it is physically reordered based on the index information. Clustering is a one-time operation: when the table is subsequently updated, the changes are not clustered. That is, no attempt is made to store new or updated rows according to their index order. (If one wishes, one can periodically recluster by issuing the command again. Also, setting the table'sfillfactor
storage parameter to less than 100% can aid in preserving cluster ordering during updates, since updated rows are kept on the same page if enough space is available there.)
When a table is clustered, PostgreSQL remembers which index it was clustered by. The formCLUSTER *
table_name*
reclusters the table using the same index as before. You can also use theCLUSTER
orSET WITHOUT CLUSTER
forms ofALTER TABLE
to set the index to be used for future cluster operations, or to clear any previous setting.
CLUSTER
without any parameter reclusters all the previously-clustered tables in the current database that the calling user owns, or all such tables if called by a superuser. This form ofCLUSTER
cannot be executed inside a transaction block.
当一个表被聚类时,一个访问独家
锁定就可以了。这可以防止任何其他数据库操作(读取和写入)对表进行操作,直到簇
完成了。
# 参数
表名
表的名称(可能是模式限定的)。
索引名称
索引的名称。
详细
在每个表都聚集在一起时打印进度报告。
布尔值
指定是否应打开或关闭所选选项。你可以写真的
,在
, 或者1
启用该选项,并且错误的
,离开
, 或者0
禁用它。这*布尔值
*value 也可以省略,在这种情况下真的
假设。
# 笔记
如果您在表中随机访问单行,则表中数据的实际顺序并不重要。但是,如果您倾向于访问某些数据而不是其他数据,并且有一个将它们组合在一起的索引,那么您将从使用簇
.如果您要从表中请求一系列索引值,或者请求具有多行匹配的单个索引值,簇
将有所帮助,因为一旦索引识别出匹配的第一行的表页,所有其他匹配的行可能已经在同一个表页上,因此您可以节省磁盘访问并加快查询速度。
簇
可以使用指定索引上的索引扫描或(如果索引是 b 树)顺序扫描然后排序来重新排序表。它将尝试根据计划者成本参数和可用的统计信息选择更快的方法。
使用索引扫描时,会创建一个表的临时副本,其中包含按索引顺序排列的表数据。还会创建表上每个索引的临时副本。因此,您需要磁盘上的可用空间至少等于表大小和索引大小的总和。
当使用顺序扫描和排序时,还会创建一个临时排序文件,因此峰值临时空间需求是表大小的两倍,再加上索引大小。这种方法通常比索引扫描方法快,但是如果磁盘空间要求不能忍受,可以通过临时设置禁用这个选项使能够_种类到离开
.
建议设置维护_工作_内存到一个相当大的值(但不超过您可以专用于簇
操作)在聚类之前。
因为规划器记录了关于表排序的统计信息,所以建议运行分析
在新聚集的表上。否则,计划者可能会做出糟糕的查询计划选择。
因为簇
记住哪些索引是集群的,可以在第一次手动集群想要集群的表,然后设置执行的定期维护脚本簇
没有任何参数,以便定期重新聚集所需的表。
每个后端运行簇
将报告其进展情况pg_stat_progress_cluster
看法。看第 28.4.4 节详情。
# 例子
对表进行聚类雇员
根据其指数employees_ind
:
CLUSTER employees USING employees_ind;
聚类雇员
使用之前使用的相同索引的表:
CLUSTER employees;
集群数据库中之前已经集群的所有表:
CLUSTER;
# 兼容性
没有簇
SQL 标准中的语句。
语法
CLUSTER index_name ON table_name
还支持与 8.3 之前的 PostgreSQL 版本兼容。