引言
索引是一种取舍:让用它的查询更快,却让每次写入更慢,因为每次插入与更新都要维护它。靠反射式加索引,会得到一个“对错误查询快、对一切写入都慢”的数据库。优化索引,是根据你运行的查询来设计:让列顺序匹配查询如何过滤与排序,让索引覆盖查询使其根本不碰表,并删除没有查询使用的索引。
索引如何被使用
B-tree 索引在其前导列上支持等值、范围与排序。当谓词匹配前导列时规划器才用它;只有当更早的列被等值约束时,才能用到更后的列。因此 (a, b) 上的索引帮助按 a 和 b 过滤的查询、或只按 a 的,但不帮只按 b 的。这就是列顺序是组合索引核心决策的原因。
从执行计划看索引使用
EXPLAIN ANALYZE 显示规划器选了哪个索引、估计行数与实际读取行数、以及是否退回顺序扫描。读取行数远多于返回行数的查询在“晚过滤”;以 Filter 而非 Index Cond 出现的过滤条件未被索引用到。这些就是“索引缺失或列序错”的信号。
组合索引的列顺序
按查询如何使用列来排序:等值列在前,范围或排序列在后。对按 customer_id 与 status 过滤、按 created_at 排序的查询,(customer_id, status, created_at) 让规划器在两个等值上 seek、并按已排序的 created_at 读行,无需额外排序。
覆盖与仅索引扫描
若索引包含查询所需的所有列,规划器可不读表而直接从索引回答,即仅索引扫描,对大表快得多。用 INCLUDE 添加额外列,使它们存于索引但不用于排序,保持搜索键干净。覆盖索引更宽、维护成本更高,故只在查询热且表大时添加。
部分索引与表达式索引
部分索引只覆盖匹配某谓词的行,更小、维护更便宜,适用于查询总是过滤到小子集(如仅未关闭订单)的场景。表达式索引覆盖计算值(如 lower(email) 或某 JSON 字段),使对表达式的查询能用索引。查询必须使用与索引相同的表达式。
索引太多
每个索引都拖慢每次写入并占空间,故无用的索引是纯成本。在统计视图里找无扫描、或扫描/写入比极低的索引,确认无人依赖后删除。(a) 与 (a, b) 重叠,较短者常冗余。把索引清单列为 schema 设计的一部分,把“加索引”当作有写入成本的决定。
结论
从你运行的查询出发优化索引:组合列按“等值在前、排序在后”,用 INCLUDE 让热查询仅索引扫描,对过滤与计算谓词用部分与表达式索引,并逐一看计划验证。然后删除无查询使用的索引,因为每个都在对写入征税。结果是一组匹配工作负载的索引,而非拖慢写入、又对无人跑的查询“优化”的反射式集合。
代码示例
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = $1
AND status = 'open'
ORDER BY created_at DESC
LIMIT 20;
-- Look for:
-- Index Scan using idx_orders_customer_created
-- Index Cond: (customer_id = ...)
-- Filter: (status = 'open') <- filtered, not indexed
-- Rows Removed by Filter: 4000 <- wasted work
-- => a better index includes status.
-- Matches the query: equality on customer_id and status, order by created_at.
CREATE INDEX idx_orders_customer_status_created
ON orders (customer_id, status, created_at DESC);
-- The same index also serves a query filtering only on customer_id (leading
-- column), but not one filtering only on status (not the leading column).
-- For that, a separate index is required:
CREATE INDEX idx_orders_status ON orders (status);
-- Covering index: search keys for filtering/ordering, INCLUDE for output.
CREATE INDEX idx_orders_covering
ON orders (customer_id, status, created_at DESC)
INCLUDE (id, total);
-- A query selecting id and total can now be answered from the index alone:
SELECT id, total
FROM orders
WHERE customer_id = $1 AND status = 'open'
ORDER BY created_at DESC
LIMIT 20;
-- Plan shows: Index Only Scan using idx_orders_covering
-- Partial index: only open orders, small and cheap to maintain.
CREATE INDEX idx_orders_open_created
ON orders (created_at DESC)
WHERE status = 'open';
-- Query must repeat the predicate: WHERE status = 'open' AND ...
-- Expression index: case-insensitive email lookup without citext.
CREATE INDEX idx_users_email_lower ON users (lower(email));
-- Query must use the same expression: WHERE lower(email) = lower($1)
-- Expression index on a JSON field for a common filter.
CREATE INDEX idx_events_kind ON events ((payload ->> 'kind'));