Files
nexus/wiki/concepts/IndexingStrategies.md
2026-05-03 05:42:12 +08:00

43 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "Indexing Strategies"
type: concept
tags: [database, postgresql, index, performance, mysql, supabase]
last_updated: 2026-05-01
---
# Indexing Strategies
## Definition
数据库索引策略是指根据查询模式和数据特征选择合适的索引类型和结构的实践方法,目的是加速数据检索同时控制写入开销和存储成本。
## Index Types
| 类型 | 适用场景 | 示例 |
|------|---------|------|
| **B-tree** | 等值查询、范围查询、排序(默认首选) | `CREATE INDEX ON users(email)` |
| **GiST** | 几何数据、全文搜索、Range 类型 | `CREATE INDEX ON documents USING GIN(to_tsvector('english', content))` |
| **GIN** | JSON/数组字段、全文搜索 | `CREATE INDEX ON posts USING GIN(metadata)` |
| **部分索引Partial** | 高频过滤条件(如下线状态) | `CREATE INDEX ON orders WHERE status = 'pending'` |
| **复合索引Composite** | 多列过滤 + 排序 | `CREATE INDEX ON posts(status, created_at DESC)` |
## Aliases
- Composite Index
- Partial Index
- Covering Index
## Key Principles
1. **外键必须加索引**:用于 JOIN 性能
2. **高频 WHERE 条件优先建索引**:但避免对低选择性列(如性别)建单列索引
3. **复合索引列顺序**:等值列在前,范围列在后
4. **避免 SELECT \***只查需要的列利于索引覆盖covering index
## Source
- [[engineering-database-optimizer]]
## Connections
- [[QueryPlanAnalysis]] — 索引效果通过 EXPLAIN ANALYZE 验证
- [[SchemaDesign]] — 索引是 Schema 设计的关键组成部分
- [[engineering-backend-architect]] — 架构设计时需考虑索引策略