本文共 1811 字,大约阅读时间需要 6 分钟。
Cluster簇管理
在PostgreSQL的统计信息表中,有一项指标correlation用于衡量heap表存储的物理顺序与索引顺序的关系。这种指标能够帮助我们了解表的数据分布情况。
以一个简单的例子为例:创建一个表tbl,字段id为主键,info字段为文本类型。执行以下SQL命令可以观察到具体情况:
dig@al=# create table tbl (id int primary key, info text);CREATE TABLE Time: 25.762 msdig@al=# insert into tbl select generate_series(1,10000), 'test';INSERT 0 10000 Time: 32.397 msdig@al=# select correlation from pg_stats where schemaname='public' and tablename='tbl' and attname='id';correlation ------------- 1 (1 row)Time: 2.648 ms
此时,correlation值为1,表示该列的物理存储顺序与索引顺序完全一致。如果值为-1,则说明索引使用了反向排序(DESC),这种情况下表的索引顺序与物理存储顺序完全相反。
为了更直观地理解这一点,我们可以执行以下操作:
dig@al=# truncate tbl;TRUNCATE TABLE Time: 34.648 msdig@al=# insert into tbl select trunc(random()*100000), 'test' from generate_series(1,100000) group by 1,2;INSERT 0 63321 Time: 332.371 msdig@al=# select correlation from pg_stats where schemaname='public' and tablename='tbl' and attname='id';correlation ------------- 0.0047608 (1 row)Time: 1.476 ms
此时,correlation值显著降低,说明物理顺序与索引顺序之间存在较大偏差。
在实际应用中,索引与物理存储顺序一致非常重要。例如,执行范围查询时,使用索引扫描可以显著减少io操作的数量。以下是一个实际操作的示例:
dig@al=# cluster tbl using tbl_pkey;CLUSTER Time: 198.924 msdig@al=# analyze tbl;ANALYZE Time: 15.418 msdig@al=# select correlation from pg_stats where schemaname='public' and tablename='tbl' and attname='id';correlation ------------- 1 (1 row)Time: 1.327 ms
此时,correlation值再次恢复为1,表明物理存储顺序与索引顺序一致。为了更直观地了解这一点,可以执行以下查询:
dig@al=# select split_part(ctid::text, ',', 1) from tbl where id between 1 and 100 group by 1 order by 1;split_part ------------ (0 (1 (103 (127 (130 (132 (134 (135 (139 (14 (143 (151 (157 (160 (164 (178 (180 (188 (189 (201 (203 (204 (22 (223 (238 (270 (272 (274 (275 (310 (314 (327 (33 (330 (334 (337 (37 (38 (40 (49 (51 (53 (60 (63 (75 (78 (8 (87 (88 (90
从结果可以看出,使用索引扫描只需要扫描一个数据块,大大降低了范围查询的heap block扫描量。
转载地址:http://mnxfk.baihongyu.com/