SELECT*FROM orders WHERE status ='processing'AND created_at > NOW() -INTERVAL'7 days' ORDERBY total_amount DESC LIMIT 100; -- 执行时间:12秒
优化步骤:
创建复合索引:
1
CREATE INDEX idx_orders_active ON orders (status, created_at, total_amount DESC);
效果: Index Scan Backward using idx_orders_active on orders (cost=0.56..153.44 rows=100 width=136)
结果:查询时间 12秒 → 0.15秒(提升80倍)
案例2:地理空间查询加速
问题:
1 2
SELECT name FROM locations WHERE ST_Distance(coords, ST_MakePoint(-74,40)) <1000; -- 全表扫描
优化:
1 2 3 4 5 6
-- 创建GiST索引 CREATE INDEX idx_locations_geo ON locations USING GIST (coords);
-- 使用索引优化查询 SELECT name FROM locations WHERE coords && ST_Buffer(ST_MakePoint(-74,40)::geography, 1000);
结果:查询时间 8.2秒 → 0.07秒
六、索引管理实践
索引设计原则:
三星标准:
1星:WHERE条件列
2星:ORDER BY/GROUP BY列
3星:覆盖SELECT所有列
监控冗余索引:
1 2 3 4 5 6 7 8
-- 查找重复索引 SELECT indrelid::regclass, indexrelid::regclass FROM pg_index WHERE indexrelid IN ( SELECT indexrelid FROM pg_stat_all_indexes WHERE idx_scan <50-- 使用次数过少 );
重建索引策略:
1 2 3 4 5
-- 在线重建(PG12+) REINDEX INDEX CONCURRENTLY idx_orders_active;