postgresql索引使用情况及坏索引处理

1、postgresql中索引系统视图pg_stat_user_indexes

TEST=# \d+ sys_stat_user_indexes
View "SYS_CATALOG.sys_stat_user_indexes"
Column | Type | Modifiers | Storage | Description
---------------+--------+-----------+---------+-------------
relid | OID | | plain |
indexrelid | OID | | plain |
schemaname | NAME | | plain |
relname | NAME | | plain |
indexrelname | NAME | | plain |
idx_scan | BIGINT | | plain |
idx_tup_read | BIGINT | | plain |
idx_tup_fetch | BIGINT | | plain |
View definition:
SELECT sys_stat_all_indexes.relid,
sys_stat_all_indexes.indexrelid,
sys_stat_all_indexes.schemaname,
sys_stat_all_indexes.relname,
sys_stat_all_indexes.indexrelname,
sys_stat_all_indexes.idx_scan,
sys_stat_all_indexes.idx_tup_read,
sys_stat_all_indexes.idx_tup_fetch
FROM sys_stat_all_indexes
WHERE (sys_stat_all_indexes.schemaname <> ALL (ARRAY['SYS_CATALOG'::NAME, 'INFORMATION_SCHEMA'::NAME])) AND sys_stat_all_indexes.schemaname !~ '^SYS_TOAST'::TEXT;

2、pg_stat_user_indexes中column含义

test=# select *from pg_stat_user_indexes;
-[ RECORD 1 ]-+----------
relid | 16447 #相关表的oid
indexrelid | 16450 #索引的oid
schemaname | public #模式名
relname | t3 #表名
indexrelname | t3_id_idx #索引名
idx_scan | 0 #通过索引扫描的次数,如果该值很小,说明该索引很少被用到,可以考虑删除
idx_tup_read | 0 #通过任意索引方法返回的索引行数
idx_tup_fetch | 0 #通过索引方法返回的数据行数

3、查看所有表的索引使用情况

select relname, indexrelname, idx_scan, idx_tup_read, idx_tup_fetch from sys_stat_user_indexes order by idx_scan asc, idx_tup_read asc, idx_tup_fetch asc;

4、查看某张表索引使用情况

select relname, indexrelname, idx_scan, idx_tup_read, idx_tup_fetch from sys_stat_user_indexes where relname = 't1' order by idx_scan asc, idx_tup_read asc,  idx_tup_read asc, idx_tup_fetch asc;

5、修复损坏索引

通过pg_dump验证到底是索引块还是表块损坏,因为pg_dump不使用索引,直接从表中获取数据。

验证故障现象

通过全表访问数据
set enable_indexscan =‘off’;
explain analzye select * from 表对象
通过索引访问数据
explain analzye select * from 表对象

a、rebuild index --该方式会锁表,DML和select都会被锁,需要根据实际业务申请维护时间
b、rebuild index concurrently --postgresl12才的功能
c、create index concurrently --并发创建索引,会使表的插入更新操作变慢,但不会锁表(推荐使用该方法)

posted @ 2021-12-23 15:35  数据库集中营  阅读(1590)  评论(0编辑  收藏  举报