REINDEX CONCURRENTLY Index Rebuild

Rebuild a bloated index with REINDEX CONCURRENTLY: writes keep flowing while the _ccnew replacement builds, and a failed run leaves an INVALID index to drop.

SqlData Fetching

Code

snippet
-- 索引因长期更新产生膨胀(bloat)后,REINDEX 原地重建(rebuild)出紧凑的物理结构;
-- 与 VACUUM FULL 相比,CONCURRENTLY 变体不阻塞并发读写:
-- 临时索引先以 _ccnew 后缀并行构建,再原子换入生效
REINDEX INDEX CONCURRENTLY products_name_trgm;

-- 一次重建一张表上的全部索引
REINDEX TABLE CONCURRENTLY products;

-- 重建中途失败会留下标记为 INVALID 的 _ccnew 索引,确认后手动清理
DROP INDEX CONCURRENTLY IF EXISTS products_name_trgm_ccnew;

-- 重建前后都用目录视图观察索引的物理大小,对比膨胀是否消除
SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
WHERE relname = 'products'
ORDER BY pg_relation_size(indexrelid) DESC;

-- 整库索引总量也可以用 pg_indexes_size 一眼看全
SELECT pg_size_pretty(pg_indexes_size('products'));

What the code does

Several statements share this file — SELECT, with pg_stat_user_indexes among the objects involved.

In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.

Applying it

Run the statement against the pg_stat_user_indexes table.

Statements that matter

SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
WHERE relname = 'products'
ORDER BY pg_relation_size(indexrelid) DESC;
SELECT pg_size_pretty(pg_indexes_size('products'));
DROP INDEX CONCURRENTLY IF EXISTS products_name_trgm_ccnew;

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
The references are `pg_stat_user_indexes`.