Token导航 LogoToken导航

Agent Skill · 研究检索

database-indexing(数据库索引)

用于辅助数据库表结构、查询语句、迁移脚本和数据维护任务。它适合让 Agent 分析 schema、编写 SQL、排查查询问题、整理索引或生成迁移建议。使用时需要明确数据库类型、连接环境和目标表,区分只读分析与写入变更;涉及删除、更新、迁移和批量导入时,应优先 dry-run、备份或事务保护,避免误操作。

database-indexing 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 63,254。

总安装 318周安装 13GitHub Stars 3下载 102核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:database-indexing(数据库索引)
来源仓库:https://github.com/1mangesh1/dev-skills-collection
仓库路径:skills/database-indexing
安装命令:
npx skills add https://github.com/1mangesh1/dev-skills-collection --skill database-indexing
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/1mangesh1/dev-skills-collection --skill database-indexing

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

深入讲解 B-tree 等索引结构原理及其在实际查询中的作用机制。解释全表扫描与索引查找的性能差异及适用场景判断。帮助理解如何通过索引减少 I/O 开销提升检索效率。适合作为基础概念学习而非直接用于生产决策支持。database-indexing 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/database-indexing

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/1mangesh1/dev-skills-collection --skill databa…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

database-indexing 怎么安装?

在终端执行 npx skills add https://github.com/1mangesh1/dev-skills-collection --skill database-indexin…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

database-indexing 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

database-indexing 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

database-indexing 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

database-indexing 用的人多吗?

公开数据是累计安装 318 次,近一周安装 13 次,下载 102 次,GitHub 3 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

database-indexing 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
database-indexing

数据库索引 · 本页

3183需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Database Indexing

What an Index Does

An index is a separate data structure that maps column values to the physical locations of rows. Without an index, the database must perform a sequential scan (full table scan), reading every row to find matches. With an index, the database navigates a much smaller structure to locate rows directly.

B-tree Structure

The default index in PostgreSQL and MySQL (InnoDB) is a B-tree -- a balanced, sorted tree where the root node contains boundary keys and pointers to child nodes, internal nodes narrow the search range at each level, and leaf nodes hold the indexed values paired with pointers to the actual table rows. Leaf nodes are linked in order, so range scans walk the leaf chain without returning to upper levels.

A lookup traverses from root to leaf in O(log n) steps. For a table with 10 million rows, a B-tree typically requires 3-4 page reads to locate a single value.

How a Lookup Works

  1. The query planner determines that an index is useful for the query.
  2. The database reads the root page and follows pointers through internal pages based on comparison with search keys.
  3. It reaches a leaf page containing the target value and a pointer to the heap (table row).
  4. It fetches the row from the heap (unless the index covers all required columns).

When to Add Indexes

Add indexes on columns that appear in:

  • WHERE clauses with equality or range conditions on selective columns.
  • JOIN conditions -- foreign key columns used in joins almost always need indexes.
  • ORDER BY / GROUP BY -- an index matching the sort order avoids a separate sort step.
  • Unique constraints -- these implicitly create indexes.

Index columns with high selectivity (many distinct values relative to row count). If a query runs frequently and scans a large portion of the table, it is a candidate. Measure before and after -- do not guess.

When NOT to Index

  • Small tables (under a few thousand rows). A sequential scan is often faster than the overhead of index lookups because the entire table fits in a few pages.
  • High-write, low-read tables (logging tables, event streams). Every INSERT, UPDATE, and DELETE must also update every index on the table.
  • Low-cardinality columns (boolean flags, status columns with 3-5 values). The index does not narrow the search enough to justify the overhead. Exception: partial indexes on a rare value can still help.
  • Columns rarely used in queries. An index that is never used wastes storage and slows writes.

Index Types

B-tree

Default in PostgreSQL and MySQL. Supports equality, range (<, >, BETWEEN), IS NULL, LIKE 'prefix%' (but not LIKE '%suffix'), and ORDER BY. Use B-tree unless you have a specific reason to choose something else.

Hash

Supports only equality comparisons (=). In PostgreSQL, hash indexes are WAL-logged since version 10 and are safe to use, but they rarely outperform B-tree. In MySQL (InnoDB), hash indexes exist only in the adaptive hash index (internal, automatic). Use hash indexes only when you are certain you will never need range queries on that column.

GIN (Generalized Inverted Index) -- PostgreSQL

Designed for values that contain multiple elements: arrays, JSONB, full-text search (tsvector), and trigram similarity. GIN indexes map each element to the set of rows containing it. They are larger and slower to update than B-tree but excel at containment queries (@>, &&, @@).

CREATE INDEX idx_tags ON articles USING gin(tags);
SELECT * FROM articles WHERE tags @> ARRAY['postgres', 'performance'];

GiST (Generalized Search Tree) -- PostgreSQL

Supports geometric data, range types, full-text search, and nearest-neighbor queries. GiST is lossy for some data types (it may return false positives that are rechecked). Use for spatial queries (<-> distance operator) and range overlap (&&).

CREATE INDEX idx_location ON places USING gist(coordinates);

BRIN (Block Range Index) -- PostgreSQL

Stores min/max summaries for each block range in the table. Extremely small index size. Effective only when physical row order correlates with column values -- common for timestamp columns on append-only tables. Useless if values are randomly distributed across pages.

CREATE INDEX idx_created ON events USING brin(created_at);

Composite Indexes

A composite (multi-column) index indexes two or more columns together.

Column Order and the Leftmost Prefix Rule

A composite index on (a, b, c) can satisfy queries that filter on:

  • a
  • a and b
  • a, b, and c

It cannot efficiently satisfy queries that filter only on b, only on c, or on b and c without a. The leftmost prefix must be present.

Choosing Column Order

  1. Place equality columns first, range columns last. A query WHERE status = 'active' AND created_at > '2025-01-01' benefits from an index on (status, created_at), not (created_at, status).
  2. If the same columns appear in different query patterns with different leading columns, you may need separate indexes.
CREATE INDEX idx_orders_status_date ON orders(status, created_at);

Partial Indexes

A partial index includes only rows that satisfy a condition. This reduces index size and maintenance cost.

CREATE INDEX idx_active_users ON users(email) WHERE active = true;

This index is used only when the query includes WHERE active = true (or a condition the planner can prove implies it). Useful for:

  • Indexing a small subset of a large table (e.g., unprocessed jobs, recent records).
  • Replacing a full index on a low-cardinality column with a filtered index on the rare value.

Partial indexes are supported in PostgreSQL. MySQL does not support them.

Covering Indexes (INCLUDE Columns)

A covering index contains all columns needed by a query, so the database never visits the heap (table) at all. This is called an index-only scan.

In PostgreSQL 11+, use INCLUDE to add non-searchable columns to the index:

CREATE INDEX idx_orders_cover ON orders(customer_id) INCLUDE (total, status);

The INCLUDE columns are stored in leaf pages but are not part of the tree structure, so they do not affect search or ordering. The query SELECT total, status FROM orders WHERE customer_id = 42 can be answered entirely from the index.

In MySQL (InnoDB), the primary key is appended to every secondary index automatically, which makes secondary indexes partially covering by default.

Expression Indexes

Index the result of a function or expression rather than a raw column value.

CREATE INDEX idx_lower_email ON users (lower(email));

This index is used only when the query matches the exact expression: WHERE lower(email) = 'user@example.com'. It will not be used for WHERE email = 'user@example.com'.

Common uses: case-insensitive lookups, extracting JSONB fields, date truncation (CREATE INDEX idx_year ON events ((extract(year FROM event_date)))).

Reading EXPLAIN and EXPLAIN ANALYZE

Basic Usage

EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;

EXPLAIN shows the planned execution without running the query. EXPLAIN ANALYZE runs the query and shows actual timings and row counts. Use EXPLAIN ANALYZE in development -- never on production with destructive statements (it executes the query).

Key Scan Types

  • Seq Scan -- reads every row in the table. Expected on small tables or non-selective filters.
  • Index Scan -- traverses the index, then fetches rows from the heap. Standard index usage.
  • Index Only Scan -- reads only the index, never visits the heap. Requires a covering index and a recently vacuumed table (visibility map must be up to date).
  • Bitmap Index Scan -- builds a bitmap of matching pages from the index, then fetches pages in physical order. Used when too many rows match for a plain index scan but too few for a sequential scan.

What to Look For

  • Large gaps between estimated rows and actual rows indicate stale statistics. Run ANALYZE.
  • Seq Scan on a large table with a selective WHERE clause suggests a missing index.
  • Sort nodes with high cost may be eliminated by an index matching the ORDER BY.
  • Nested loop joins on unindexed columns produce O(n*m) behavior.

Index Maintenance

Bloat

UPDATE and DELETE operations in PostgreSQL do not remove index entries immediately. Dead tuples accumulate, causing index bloat. Autovacuum cleans up dead tuples, but under heavy write loads it may fall behind.

Monitor bloat:

SELECT schemaname, relname, indexrelname,
       pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
ORDER BY pg_relation_size(indexrelid) DESC;

REINDEX

Rebuilds an index from scratch, removing bloat. Locks the table for writes in standard mode. Use REINDEX CONCURRENTLY (PostgreSQL 12+) for online rebuilds.

REINDEX INDEX CONCURRENTLY idx_orders_status_date;

Finding Unused Indexes

SELECT indexrelname, idx_scan, pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;

Indexes with zero scans since the last statistics reset are candidates for removal. Verify no rare but critical queries depend on them before dropping.

MySQL vs PostgreSQL Index Differences

FeaturePostgreSQLMySQL (InnoDB)
Clustered indexOptional (via CLUSTER)Always on primary key
Secondary indexesPoint to heap tuple (ctid)Store the primary key value
Partial indexesSupportedNot supported
Expression indexesSupportedSupported (8.0.13+, functional indexes)
INCLUDE columnsSupported (11+)Not supported
GIN, GiST, BRINSupportedNot available
Hash indexesWAL-logged, explicitAdaptive hash index (internal only)
Online DDLCREATE INDEX CONCURRENTLYALTER TABLE... ALGORITHM=INPLACE
Covering index syntaxINCLUDE (cols)All InnoDB indexes include PK

In MySQL InnoDB, the table is a clustered B-tree ordered by primary key. Secondary index lookups require a second traversal (secondary index to PK, then PK to row), making primary key choice critical -- use a compact, auto-incrementing integer.

MongoDB Indexes

Single Field and Compound Indexes

db.orders.createIndex({ customer_id: 1 });
db.orders.createIndex({ customer_id: 1, created_at: -1 });

Compound indexes follow the same leftmost prefix rule as relational databases. The direction (1 ascending, -1 descending) matters for sort operations.

Text Indexes

db.articles.createIndex({ title: "text", body: "text" });

One text index per collection. Supports language-specific stemming and stop words.

TTL Indexes

Automatically delete documents after a specified time. Only works on Date fields, single-field only:

db.sessions.createIndex({ created_at: 1 }, { expireAfterSeconds: 3600 });

Sparse and Partial Filter Indexes

Sparse indexes include only documents where the field exists, reducing index size. Prefer partialFilterExpression (MongoDB 3.2+) for more control:

db.users.createIndex({ phone: 1 }, { partialFilterExpression: { phone: { $exists: true } } });

Common Anti-patterns

Indexing every column. Each index consumes storage and slows every write. A table with 15 indexes on 20 columns is almost certainly over-indexed.

Redundant indexes. An index on (a, b) makes a separate index on (a) redundant, because the composite index satisfies single-column lookups on a. Check for these and remove them.

Unused indexes. Query pg_stat_user_indexes (PostgreSQL) or sys.schema_unused_indexes (MySQL performance_schema) regularly. Drop indexes that have zero scans over a meaningful time period.

Indexing for queries that do not exist. Adding indexes based on schema rather than actual query patterns leads to waste. Index based on measured workload.

Ignoring index impact on writes. Every INSERT must update every index. On write-heavy tables, excessive indexing directly causes poor write throughput.

Index Impact on Writes

For each INSERT:

  • One write to the heap (table).
  • One write per index (B-tree insertion, possible page split).

For each UPDATE on an indexed column:

  • The old index entry is marked dead (PostgreSQL) or removed (MySQL).
  • A new index entry is inserted.

For each DELETE:

  • All index entries for that row must be cleaned up.

In PostgreSQL, HOT (Heap-Only Tuple) updates avoid index updates when the updated columns are not indexed and the new tuple fits on the same page. This is a strong argument against indexing columns that are frequently updated.

Benchmark write throughput before and after adding indexes on write-heavy tables.

Practical Example: Diagnosing and Fixing a Slow Query

Symptom: The following query takes 4 seconds on a table with 5 million rows:

SELECT id, email, created_at
FROM users
WHERE status = 'active' AND created_at > '2025-01-01'
ORDER BY created_at DESC
LIMIT 20;

Step 1: Run EXPLAIN ANALYZE. Output shows Seq Scan on users, actual time 3800ms, rows removed by filter: 4,200,000.

Step 2: Identify the problem. Full table scan. No index on status or created_at.

Step 3: Choose the right index. The query filters on status (equality) and created_at (range), then sorts by created_at. A composite index with the equality column first:

CREATE INDEX idx_users_status_created ON users(status, created_at DESC);

Step 4: Consider a covering index to avoid heap fetches:

CREATE INDEX idx_users_status_created_cover
ON users(status, created_at DESC) INCLUDE (email);

Step 5: Verify with EXPLAIN ANALYZE again. Expected result: Index Only Scan (or Index Scan), actual time under 1ms, reads only 20 rows from the index.

Step 6: Monitor. Check pg_stat_user_indexes after deployment to confirm the new index is being used and that it did not introduce regression on write operations.

References

平台分布

Codex

36.77%
按下载量换算38

Claude

31.14%
按下载量换算32

Cursor

18.7%
按下载量换算19

Gemini CLI

9.73%
按下载量换算10

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills