Postgresql Indexing 标志

Postgresql Indexing

组织热门
prowler-cloud
postgresql-indexing

Prowler 的 PostgreSQL 索引最佳实践:索引设计、部分索引、分区表索引、使用 EXPLAIN ANALYZE 验证、并发操作、监控和维护。触发条件:创建或修改 PostgreSQL 索引、使用 EXPLAIN 分析查询性能、排查慢查询、审查索引使用统计信息、重建索引、删除索引,或处理分区表索引时。讨论索引策略、部分索引,或 VACUUM、ANALYZE 等索引维护操作时也会触发。

Add to TypingMind

概览

发布者prowler-cloud
代码仓库prowler
技能名称postgresql-indexing
星标数
14.8K
复刻数
2.4K
附带文件
仅含指令
许可协议Apache-2.0
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 prowler-cloud 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Postgresql Indexing AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/prowler-cloud/prowler/tree/master/skills/postgresql-indexing
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/prowler-cloud/prowler.git /tmp/prowler
mkdir -p .claude/skills
cp -r /tmp/prowler/skills/postgresql-indexing .claude/skills/postgresql-indexing
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Postgresql Indexing,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Postgresql Indexing。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Postgresql Indexing 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

When to use

  • Creating or modifying PostgreSQL indexes
  • Analyzing query plans with EXPLAIN
  • Debugging slow queries or missing index usage
  • Dropping, reindexing, or validating indexes
  • Working with indexes on partitioned tables (findings, resource_finding_mappings)
  • Running VACUUM or ANALYZE after index changes

Index design

Partial indexes: constant columns go in WHERE, not in the key

When a column has a fixed value for the query (e.g., state = 'completed'), put it in the WHERE clause of the index, not in the indexed columns. Otherwise the planner cannot exploit the ordering of the other columns.

sql
-- Bad: state in the key wastes space and breaks ordering
CREATE INDEX idx_scans_tenant_state ON scans (tenant_id, state, inserted_at DESC);

-- Good: state as a filter, planner uses tenant_id + inserted_at ordering
CREATE INDEX idx_scans_tenant_ins_completed ON scans (tenant_id, inserted_at DESC)
    WHERE state = 'completed';

Column order matters

Put high-selectivity columns first (columns that filter out the most rows). For composite indexes, the leftmost column must appear in the query's WHERE clause for the index to be used.

Validating index effectiveness

Always EXPLAIN (ANALYZE, BUFFERS) after adding indexes

Never assume an index is being used. Run EXPLAIN (ANALYZE, BUFFERS) to confirm.

sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM users
WHERE email = 'user@example.com';

Use Postgres EXPLAIN Visualizer (pev) to visualize query plans and identify bottlenecks.

Force index usage for testing

The planner may choose a sequential scan on small datasets. Toggle enable_seqscan = off to confirm the index path works, then re-enable it.

sql
SET enable_seqscan = off;

EXPLAIN (ANALYZE, BUFFERS)
SELECT DISTINCT ON (provider_id) provider_id
FROM scans
WHERE tenant_id = '95383b24-da01-44b5-a713-0d9920d554db'
  AND state = 'completed'
ORDER BY provider_id, inserted_at DESC;

SET enable_seqscan = on;  -- always re-enable after testing

This is for validation only. Never leave enable_seqscan = off in production.

Over-indexing

Every extra index has three costs that compound:

  1. Write overhead. Every INSERT and UPDATE must maintain all indexes. Extra indexes also kill HOT (Heap-Only-Tuple) updates, which normally skip index maintenance when unindexed columns change.

  2. Planning time. The planner evaluates more execution paths per index. On simple OLTP queries, planning time can exceed execution time by 4x when index count is high.

  3. Lock contention (fastpath limit). PostgreSQL uses a fast path for the first 16 locks per backend. After 16 relations (table + its indexes), it falls back to slower LWLock mechanisms. At high QPS (100+), this causes LockManager wait events.

Rules:

  • Drop unused and redundant indexes regularly
  • Be especially careful with partitioned tables (each partition multiplies the index count)
  • Use prepared statements to reduce planning overhead when index count is high

Finding redundant indexes

Two indexes are redundant when:

  • They have the same columns in the same order (duplicates)
  • One is a prefix of the other: index (a) is redundant to (a, b), but NOT to (b, a)

Column order matters. For partial indexes, the WHERE clause must also match.

sql
-- Quick check: find indexes that share a leading column on the same table
SELECT
    a.indrelid::regclass AS table_name,
    a.indexrelid::regclass AS index_a,
    b.indexrelid::regclass AS index_b,
    pg_size_pretty(pg_relation_size(a.indexrelid)) AS size_a,
    pg_size_pretty(pg_relation_size(b.indexrelid)) AS size_b
FROM pg_index a
JOIN pg_index b ON a.indrelid = b.indrelid
    AND a.indexrelid != b.indexrelid
    AND a.indkey::text = (
        SELECT string_agg(x::text, ' ')
        FROM unnest(b.indkey[:array_length(a.indkey, 1)]) AS x
    )
WHERE NOT a.indisunique;

Before dropping: verify on all workload nodes (primary + replicas), use DROP INDEX CONCURRENTLY, and monitor for plan regressions.

Monitoring index usage

Identify unused indexes

Query pg_stat_all_indexes to find indexes that are never or rarely scanned:

sql
SELECT
    idxstat.schemaname AS schema_name,
    idxstat.relname AS table_name,
    idxstat.indexrelname AS index_name,
    idxstat.idx_scan AS index_scans_count,
    idxstat.last_idx_scan AS last_idx_scan_timestamp,
    pg_size_pretty(pg_relation_size(idxstat.indexrelid)) AS index_size
FROM pg_stat_all_indexes AS idxstat
JOIN pg_index i ON idxstat.indexrelid = i.indexrelid
WHERE idxstat.schemaname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
  AND NOT i.indisunique
ORDER BY idxstat.idx_scan ASC, idxstat.last_idx_scan ASC;

Indexes with idx_scan = 0 and no recent last_idx_scan are candidates for removal.

Before dropping, verify:

  • Stats haven't been reset recently (check stats_reset in pg_stat_database)
  • Stats cover at least 1 month of production traffic
  • All workload nodes (primary + replicas) have been checked
  • The index isn't used by a periodic job that runs infrequently
sql
-- Check when stats were last reset
SELECT stats_reset, age(now(), stats_reset)
FROM pg_stat_database
WHERE datname = current_database();

Monitor index creation progress

Do not assume index creation succeeded. Use pg_stat_progress_create_index (Postgres 12+) to watch progress live:

sql
SELECT * FROM pg_stat_progress_create_index;

In psql, use \watch 5 to refresh every 5 seconds for a live dashboard view. CREATE INDEX CONCURRENTLY and REINDEX CONCURRENTLY have more phases than standard operations: monitor for blocking sessions and wait events.

Validate index integrity

Check for invalid indexes regularly:

sql
SELECT c.relname AS index_name, i.indisvalid
FROM pg_class c
JOIN pg_index i ON i.indexrelid = c.oid
WHERE i.indisvalid = false;

Invalid indexes are ignored by the planner. They waste space and cause inconsistent query performance, especially on partitioned tables where some partitions may have valid indexes and others do not.

Concurrent operations

Always use CONCURRENTLY in production

Never create or drop indexes without CONCURRENTLY on live tables. Without it, the operation holds a lock that blocks all writes.

sql
-- Create
CREATE INDEX CONCURRENTLY IF NOT EXISTS index_name ON table_name (column_name);

-- Drop
DROP INDEX CONCURRENTLY IF EXISTS index_name;

DROP INDEX CONCURRENTLY cannot run inside a transaction block.

Always use IF NOT EXISTS / IF EXISTS

Makes scripts idempotent. Safe to re-run without errors from duplicate or missing indexes.

Concurrent indexing can fail silently

CREATE INDEX CONCURRENTLY can fail without raising an error. The result is an invalid index that the planner ignores. This is particularly dangerous on partitioned tables: some partitions get valid indexes, others don't, causing inconsistent query performance.

After any concurrent index creation, always validate:

sql
SELECT c.relname, i.indisvalid
FROM pg_class c
JOIN pg_index i ON i.indexrelid = c.oid
WHERE c.relname LIKE '%your_index_name%';

Reindexing invalid indexes

Rebuild invalid indexes without locking writes:

sql
REINDEX INDEX CONCURRENTLY index_name;

Understanding _ccnew and_ccold artifacts

When CREATE INDEX CONCURRENTLY or REINDEX INDEX CONCURRENTLY is interrupted, temporary indexes may remain:

SuffixMeaningAction
_ccnewNew index being built, incompleteDrop it and retry REINDEX CONCURRENTLY
_ccoldOld index being replaced, rebuild succeededSafe to drop
sql
-- Example: both original and temp are invalid
-- users_emails_2019       btree (col) INVALID
-- users_emails_2019_ccnew btree (col) INVALID

-- Drop the failed new one, then retry
DROP INDEX CONCURRENTLY IF EXISTS users_emails_2019_ccnew;
REINDEX INDEX CONCURRENTLY users_emails_2019;

These leftovers clutter the schema, confuse developers, and waste disk space. Clean them up.

Indexing partitioned tables

Do NOT use ALTER INDEX ATTACH PARTITION

As stated in PostgreSQL documentation, ALTER INDEX ... ATTACH PARTITION prevents dropping malfunctioning or non-performant indexes from individual partitions. An attached index cannot be dropped by itself and is automatically dropped if its parent index is dropped.

This removes the ability to manage indexes per-partition, which we need for:

  • Dropping broken indexes on specific partitions
  • Skipping indexes on old partitions to save storage
  • Rebuilding indexes on individual partitions without affecting others

Correct approach: create on partitions, then on parent

  1. Create the index on each child partition concurrently:
sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_child_partition
    ON child_partition (column_name);
  1. Create the index on the parent table (metadata-only, fast):
sql
CREATE INDEX IF NOT EXISTS idx_parent
    ON parent_table (column_name);

PostgreSQL will automatically recognize partition-level indexes as part of the parent index definition when the index names and definitions match.

Prioritize active partitions

For time-based partitions (findings uses monthly partitions):

  • Create indexes on recent/current partitions where data is actively queried
  • Skip older partitions that are rarely accessed
  • The all_partitions=False default in create_index_on_partitions handles this automatically

Index maintenance and bloat

Over time, B-tree indexes accumulate bloat from updates and deletes. VACUUM reclaims heap space but does NOT rebalance B-tree pages. Periodic reindexing is necessary for heavily updated tables.

Detecting bloat

Indexes with estimated bloat above 50% are candidates for REINDEX CONCURRENTLY. Check bloat with tools like pgstattuple or bloat estimation queries.

Reducing bloat buildup

Three things slow degradation:

  1. Upgrade to PostgreSQL 14+ for B-tree deduplication and bottom-up deletion
  2. Maximize HOT updates by not indexing frequently-updated columns
  3. Tune autovacuum to run more aggressively on high-churn tables

Rebuilding many indexes without deadlocks

If you rebuild two indexes on the same table in parallel, PostgreSQL detects a deadlock and kills one session. To rebuild many indexes across multiple sessions safely, assign all indexes for a given table to the same session:

sql
\set NUMBER_OF_SESSIONS 10

SELECT
    format('%I.%I', n.nspname, c.relname) AS table_fqn,
    format('%I.%I', n.nspname, i.relname) AS index_fqn,
    mod(
        hashtext(format('%I.%I', n.nspname, c.relname)) & 2147483647,
        :NUMBER_OF_SESSIONS
    ) AS session_id
FROM pg_index idx
JOIN pg_class c ON idx.indrelid = c.oid
JOIN pg_class i ON idx.indexrelid = i.oid
JOIN pg_namespace n ON c.relnamespace = n.oid
WHERE n.nspname NOT IN ('pg_catalog', 'pg_toast', 'information_schema')
ORDER BY table_fqn, index_fqn;

Then run each session's indexes in a separate REINDEX INDEX CONCURRENTLY call. Set NUMBER_OF_SESSIONS based on max_parallel_maintenance_workers and available I/O.

Dropping indexes

Post-drop maintenance

After dropping an index, run VACUUM and ANALYZE to reclaim space and update planner statistics:

sql
-- Full vacuum + analyze (can be heavy on large tables)
VACUUM (ANALYZE) your_table;

-- Lightweight alternative for huge tables: just update statistics
ANALYZE your_table;

Commands

sql
-- Validate query uses an index
EXPLAIN (ANALYZE, BUFFERS) SELECT ...;

-- Check index creation progress
SELECT * FROM pg_stat_progress_create_index;

-- Find invalid indexes
SELECT c.relname, i.indisvalid
FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid
WHERE i.indisvalid = false;

-- Find unused indexes
SELECT relname, indexrelname, idx_scan, pg_size_pretty(pg_relation_size(indexrelid))
FROM pg_stat_all_indexes
WHERE schemaname = 'public' AND idx_scan = 0;

-- Create index safely
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_name ON table (columns);

-- Drop index safely
DROP INDEX CONCURRENTLY IF EXISTS idx_name;

-- Rebuild invalid index
REINDEX INDEX CONCURRENTLY idx_name;

-- Post-drop maintenance
VACUUM (ANALYZE) table_name;

Context7 lookups

Prerequisite: Install Context7 MCP server for up-to-date documentation lookup.

LibraryContext7 IDUse for
PostgreSQL/websites/postgresql_org_docs_currentIndex types, EXPLAIN, partitioned table indexing, REINDEX

Example queries:

text
mcp_context7_query-docs(libraryId="/websites/postgresql_org_docs_current", query="CREATE INDEX CONCURRENTLY partitioned table")
mcp_context7_query-docs(libraryId="/websites/postgresql_org_docs_current", query="EXPLAIN ANALYZE BUFFERS query plan")
mcp_context7_query-docs(libraryId="/websites/postgresql_org_docs_current", query="partial index WHERE clause")
mcp_context7_query-docs(libraryId="/websites/postgresql_org_docs_current", query="REINDEX CONCURRENTLY invalid index")
mcp_context7_query-docs(libraryId="/websites/postgresql_org_docs_current", query="pg_stat_all_indexes monitoring")

Note: Use mcp_context7_resolve-library-id first if you need to find the correct library ID.

Resources

  • EXPLAIN Visualizer: pev

常见问题

Postgresql Indexing AI 技能有什么作用?

Prowler 的 PostgreSQL 索引最佳实践:索引设计、部分索引、分区表索引、使用 EXPLAIN ANALYZE 验证、并发操作、监控和维护。触发条件:创建或修改 PostgreSQL 索引、使用 EXPLAIN 分析查询性能、排查慢查询、审查索引使用统计信息、重建索引、删除索引,或处理分区表索引时。讨论索引策略、部分索引,或 VACUUM、ANALYZE 等索引维护操作时也会触发。

为什么在 TypingMind 中使用 Postgresql Indexing?

因为您只需安装一次,就能搭配任何模型使用。Postgresql Indexing 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Postgresql Indexing?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/prowler-cloud/prowler/tree/master/skills/postgresql-indexing。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Postgresql Indexing?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Postgresql Indexing 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Postgresql Indexing 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Postgresql Indexing AI 技能免费吗?

是的。prowler-cloud 已在 GitHub 上根据 Apache-2.0 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇