pg_statio_user_indexes Measures Index Cache Hits
Compare idx_blks_hit with idx_blks_read in pg_statio_user_indexes to compute a per-index cache hit ratio and spot indexes missing the shared buffers.
Code
-- 每个用户索引一行:idx_blks_hit 是共享缓冲命中块数,idx_blks_read 是未命中的读取
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id integer NOT NULL,
at timestamptz NOT NULL
);
CREATE INDEX idx_events_tenant ON events (tenant_id);
INSERT INTO events (tenant_id, at)
SELECT g % 16, now() - (g || ' minutes')::interval
FROM generate_series(1, 5000) AS g;
-- 制造真实访问:走索引的查询会被记入 idx_blks_hit
SELECT count(*) FROM events WHERE tenant_id = 3;
-- 每索引缓存命中率:hit / (hit + read),越高说明索引越常驻共享缓冲
SELECT
schemaname,
relname,
indexrelname,
idx_blks_read,
idx_blks_hit,
round(100.0 * idx_blks_hit / nullif(idx_blks_hit + idx_blks_read, 0), 1) AS hit_pct
FROM pg_statio_user_indexes
WHERE relname = 'events'
ORDER BY hit_pct DESC;
-- 注意:*_read 包含内核页缓存命中,不完全等于物理磁盘 I/O(文档明确说明)
-- 持续低命中率再结合 pg_stat_user_indexes.idx_scan 判断去留How it works
SELECT / INSERT / CREATE statements share the script, touching events, generate_series and pg_statio_user_indexes.
In terms of clauses, the statements use: a WHERE clause that picks out the rows one statement touches; COUNT aggregation; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Run the statement against the events table.
Statements that matter most here
SELECT
schemaname,
relname,
indexrelname,
idx_blks_read,
idx_blks_hit,
round(100.0 * idx_blks_hit / nullif(idx_blks_hit + idx_blks_read, 0), 1) AS hit_pct
FROM pg_statio_user_indexes
WHERE relname = 'events'
ORDER BY hit_pct DESC;
INSERT INTO events (tenant_id, at)
SELECT g % 16, now() - (g || ' minutes')::interval
FROM generate_series(1, 5000) AS g;
SELECT count(*) FROM events WHERE tenant_id = 3;
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.
FAQ
- Which tables or CTEs does it reference?
- The references are `events`, `generate_series`, `pg_statio_user_indexes`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.