# 索引

> 英文标题：Indexes
> 官网原文：https://typeorm.io/docs/performance-optimization/using-indexes
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 79 块

---

<!-- EN -->
# Using indexes

<!-- ZH -->
# 使用索引

<!-- EN -->
Indexes are data structures that allow the database to locate rows without scanning the entire table. Without an index, a query must examine every row to find matches. With an index, the database can jump directly to the relevant rows — dramatically reducing the number of rows examined.

<!-- ZH -->
索引是一种数据结构，它让数据库无需扫描整张表就能定位到行。没有索引时，查询必须检查每一行来寻找匹配项。有了索引，数据库可以直接跳到相关的行——大幅减少被检查的行数。

<!-- EN -->
Indexes accelerate read operations but add overhead to writes (inserts, updates, deletes) since the index must be kept in sync, so they should be created carefully and only when needed.

<!-- ZH -->
索引能加速读操作，但会给写操作（插入、更新、删除）带来额外开销，因为索引必须保持同步，所以应当谨慎创建、仅在需要时创建。

<!-- EN -->
Good candidates for indexes are columns frequently used in `WHERE` clauses, joins, and sorting. When more than one column is used as a filter, it might make sense to create a [composite index](https://typeorm.io/docs/indexes#indexes-with-multiple-columns), however bear in mind that column order matters — place the most selective (most unique values) columns first.

<!-- ZH -->
适合建索引的候选列，是那些经常出现在 `WHERE` 子句、连接和排序中的列。当有多个列被用作过滤条件时，创建[复合索引](https://typeorm.io/docs/indexes#indexes-with-multiple-columns)可能有意义，不过请记住列的顺序很重要——把选择性最高（唯一值最多）的列放在最前面。

<!-- EN -->
## Analyzing query performance

<!-- ZH -->
## 分析查询性能

<!-- EN -->
Most databases let you inspect how a query is being executed, which is called an execution plan. Understanding such a plan helps you identify missing indexes and optimize how a query is constructed by comparing various ways of fetching the same data.

<!-- ZH -->
大多数数据库都允许你查看一条查询是如何被执行的，这被称为执行计划。理解这样的计划有助于你找出缺失的索引，并通过比较获取同一数据的各种方式来优化查询的构造方式。

<!-- EN -->
* ![CockroachDB](/img/databases/cockroachdb.svg "CockroachDB")
* ![Google Spanner](/img/databases/spanner.svg "Google Spanner")
* ![MariaDB](/img/databases/mariadb.svg "MariaDB")
* ![MongoDB](/img/databases/mongodb.svg "MongoDB")
* ![MS SQL Server](/img/databases/mssql.svg "MS SQL Server")
* ![MySQL](/img/databases/mysql.svg "MySQL")
* ![Oracle](/img/databases/oracle.svg "Oracle")
* ![PostgreSQL](/img/databases/postgresql.svg "PostgreSQL")
* ![SAP HANA](/img/databases/sap.svg "SAP HANA")
* ![SQLite](/img/databases/sqlite.svg "SQLite")

<!-- ZH -->
* ![CockroachDB](/img/databases/cockroachdb.svg "CockroachDB")
* ![Google Spanner](/img/databases/spanner.svg "Google Spanner")
* ![MariaDB](/img/databases/mariadb.svg "MariaDB")
* ![MongoDB](/img/databases/mongodb.svg "MongoDB")
* ![MS SQL Server](/img/databases/mssql.svg "MS SQL Server")
* ![MySQL](/img/databases/mysql.svg "MySQL")
* ![Oracle](/img/databases/oracle.svg "Oracle")
* ![PostgreSQL](/img/databases/postgresql.svg "PostgreSQL")
* ![SAP HANA](/img/databases/sap.svg "SAP HANA")
* ![SQLite](/img/databases/sqlite.svg "SQLite")

<!-- EN -->
### CockroachDB

<!-- ZH -->
### CockroachDB

<!-- EN -->
Use `EXPLAIN ANALYZE` (same syntax as PostgreSQL):

<!-- ZH -->
使用 `EXPLAIN ANALYZE`（语法与 PostgreSQL 相同）：

<!-- EN -->
```sql
EXPLAIN ANALYZE SELECT * FROM "user" WHERE "firstName" = 'Timber';
```

<!-- ZH -->
```sql
EXPLAIN ANALYZE SELECT * FROM "user" WHERE "firstName" = 'Timber';
```

<!-- EN -->
Look for `full scan` (no index) vs `scan` with a specific index name.

<!-- ZH -->
留意 `full scan`（无索引）与带具体索引名的 `scan` 之间的区别。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Indexes](https://www.cockroachlabs.com/docs/stable/indexes.html)
* [EXPLAIN](https://www.cockroachlabs.com/docs/stable/explain.html)

<!-- ZH -->
* [Indexes](https://www.cockroachlabs.com/docs/stable/indexes.html)
* [EXPLAIN](https://www.cockroachlabs.com/docs/stable/explain.html)

<!-- EN -->
### Google Spanner

<!-- ZH -->
### Google Spanner

<!-- EN -->
Use the [Query Plan visualizer](https://cloud.google.com/spanner/docs/query-execution-plans#query_plan_visualizer) in the Google Cloud Console, or run a query in `PLAN`/`PROFILE` mode via the `gcloud` CLI:

<!-- ZH -->
在 Google Cloud Console 中使用 [Query Plan visualizer](https://cloud.google.com/spanner/docs/query-execution-plans#query_plan_visualizer)，或者通过 `gcloud` CLI 以 `PLAN`/`PROFILE` 模式运行查询：

<!-- EN -->
```bash
gcloud spanner databases execute-sql DATABASE_ID \
    --instance=INSTANCE_ID \
    --query-mode=PROFILE \
    --sql="SELECT * FROM user WHERE firstName = 'Timber'"
```

<!-- ZH -->
```bash
gcloud spanner databases execute-sql DATABASE_ID \
    --instance=INSTANCE_ID \
    --query-mode=PROFILE \
    --sql="SELECT * FROM user WHERE firstName = 'Timber'"
```

<!-- EN -->
Look for `Table Scan` (no index) vs `Index Scan` in the returned plan.

<!-- ZH -->
在返回的计划中留意 `Table Scan`（无索引）与 `Index Scan` 的区别。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Secondary Indexes](https://cloud.google.com/spanner/docs/secondary-indexes)
* [Query Execution Plans](https://cloud.google.com/spanner/docs/query-execution-plans)

<!-- ZH -->
* [Secondary Indexes](https://cloud.google.com/spanner/docs/secondary-indexes)
* [Query Execution Plans](https://cloud.google.com/spanner/docs/query-execution-plans)

<!-- EN -->
### MariaDB

<!-- ZH -->
### MariaDB

<!-- EN -->
Use `EXPLAIN` or `ANALYZE` to inspect the query execution plan:

<!-- ZH -->
使用 `EXPLAIN` 或 `ANALYZE` 查看查询执行计划：

<!-- EN -->
```sql
ANALYZE SELECT * FROM user WHERE firstName = 'Timber';
```

<!-- ZH -->
```sql
ANALYZE SELECT * FROM user WHERE firstName = 'Timber';
```

<!-- EN -->
Check the `type` column — `ALL` means a full table scan, while `ref`, `range`, or `index` indicate index usage. The `key` column shows which index was chosen.

<!-- ZH -->
检查 `type` 列——`ALL` 表示全表扫描，而 `ref`、`range` 或 `index` 表示用到了索引。`key` 列显示选择了哪个索引。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Optimization and Indexes](https://mariadb.com/kb/en/optimization-and-indexes/)
* [EXPLAIN](https://mariadb.com/kb/en/explain/)
* [ANALYZE Statement](https://mariadb.com/kb/en/analyze-statement/)

<!-- ZH -->
* [Optimization and Indexes](https://mariadb.com/kb/en/optimization-and-indexes/)
* [EXPLAIN](https://mariadb.com/kb/en/explain/)
* [ANALYZE Statement](https://mariadb.com/kb/en/analyze-statement/)

<!-- EN -->
### MongoDB

<!-- ZH -->
### MongoDB

<!-- EN -->
Use the `explain()` method on a query to see the execution plan:

<!-- ZH -->
在查询上使用 `explain()` 方法查看执行计划：

<!-- EN -->
```javascript
db.user.find({ firstName: "Timber" }).explain("executionStats")
```

<!-- ZH -->
```javascript
db.user.find({ firstName: "Timber" }).explain("executionStats")
```

<!-- EN -->
Look for `COLLSCAN` (collection scan — no index) vs `IXSCAN` (index scan).

<!-- ZH -->
留意 `COLLSCAN`（集合扫描——无索引）与 `IXSCAN`（索引扫描）的区别。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Indexes](https://www.mongodb.com/docs/manual/indexes/)
* [Explain Results](https://www.mongodb.com/docs/manual/reference/explain-results/)

<!-- ZH -->
* [Indexes](https://www.mongodb.com/docs/manual/indexes/)
* [Explain Results](https://www.mongodb.com/docs/manual/reference/explain-results/)

<!-- EN -->
### MS SQL Server

<!-- ZH -->
### MS SQL Server

<!-- EN -->
Use the execution plan to analyze queries. In SQL Server Management Studio, press `Ctrl+M` to include the actual execution plan, then run your query. Programmatically:

<!-- ZH -->
使用执行计划分析查询。在 SQL Server Management Studio 中，按 `Ctrl+M` 包含实际执行计划，然后运行你的查询。以编程方式：

<!-- EN -->
```sql
SET STATISTICS IO ON;
SELECT * FROM [user] WHERE firstName = 'Timber';
SET STATISTICS IO OFF;
```

<!-- ZH -->
```sql
SET STATISTICS IO ON;
SELECT * FROM [user] WHERE firstName = 'Timber';
SET STATISTICS IO OFF;
```

<!-- EN -->
Look for `Table Scan` (no index) vs `Index Seek` or `Index Scan` in the execution plan.

<!-- ZH -->
在执行计划中留意 `Table Scan`（无索引）与 `Index Seek` 或 `Index Scan` 的区别。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Indexes](https://learn.microsoft.com/en-us/sql/relational-databases/indexes/indexes)
* [Execution Plans](https://learn.microsoft.com/en-us/sql/relational-databases/performance/execution-plans)

<!-- ZH -->
* [Indexes](https://learn.microsoft.com/en-us/sql/relational-databases/indexes/indexes)
* [Execution Plans](https://learn.microsoft.com/en-us/sql/relational-databases/performance/execution-plans)

<!-- EN -->
### MySQL

<!-- ZH -->
### MySQL

<!-- EN -->
Use `EXPLAIN` to inspect the query execution plan:

<!-- ZH -->
使用 `EXPLAIN` 查看查询执行计划：

<!-- EN -->
```sql
EXPLAIN SELECT * FROM user WHERE firstName = 'Timber';
```

<!-- ZH -->
```sql
EXPLAIN SELECT * FROM user WHERE firstName = 'Timber';
```

<!-- EN -->
Check the `type` column — `ALL` means a full table scan, while `ref`, `range`, or `index` indicate index usage. The `key` column shows which index was chosen.

<!-- ZH -->
检查 `type` 列——`ALL` 表示全表扫描，而 `ref`、`range` 或 `index` 表示用到了索引。`key` 列显示选择了哪个索引。

<!-- EN -->
Aurora MySQL

<!-- ZH -->
Aurora MySQL

<!-- EN -->
This also applies to Amazon Aurora MySQL, which uses the same query engine and EXPLAIN syntax. See [Aurora MySQL tuning](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Managing.Tuning.html) for Aurora-specific guidance.

<!-- ZH -->
这同样适用于 Amazon Aurora MySQL，它使用相同的查询引擎和 EXPLAIN 语法。Aurora 专属的指导请参阅 [Aurora MySQL 调优](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Managing.Tuning.html)。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Optimization and Indexes](https://dev.mysql.com/doc/refman/en/optimization-indexes.html)
* [EXPLAIN Output Format](https://dev.mysql.com/doc/refman/en/explain-output.html)

<!-- ZH -->
* [Optimization and Indexes](https://dev.mysql.com/doc/refman/en/optimization-indexes.html)
* [EXPLAIN Output Format](https://dev.mysql.com/doc/refman/en/explain-output.html)

<!-- EN -->
### Oracle

<!-- ZH -->
### Oracle

<!-- EN -->
Use `EXPLAIN PLAN` to inspect the execution plan:

<!-- ZH -->
使用 `EXPLAIN PLAN` 查看执行计划：

<!-- EN -->
```sql
EXPLAIN PLAN FOR SELECT * FROM "user" WHERE "firstName" = 'Timber';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
```

<!-- ZH -->
```sql
EXPLAIN PLAN FOR SELECT * FROM "user" WHERE "firstName" = 'Timber';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
```

<!-- EN -->
Look for `TABLE ACCESS FULL` (no index) vs `INDEX RANGE SCAN` or `INDEX UNIQUE SCAN`.

<!-- ZH -->
留意 `TABLE ACCESS FULL`（无索引）与 `INDEX RANGE SCAN` 或 `INDEX UNIQUE SCAN` 的区别。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Indexes and Index-Organized Tables](https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/indexes-and-index-organized-tables.html)
* [Generating and Displaying Execution Plans](https://docs.oracle.com/en/database/oracle/oracle-database/23/tgsql/generating-and-displaying-execution-plans.html)

<!-- ZH -->
* [Indexes and Index-Organized Tables](https://docs.oracle.com/en/database/oracle/oracle-database/23/cncpt/indexes-and-index-organized-tables.html)
* [Generating and Displaying Execution Plans](https://docs.oracle.com/en/database/oracle/oracle-database/23/tgsql/generating-and-displaying-execution-plans.html)

<!-- EN -->
### PostgreSQL

<!-- ZH -->
### PostgreSQL

<!-- EN -->
Use `EXPLAIN ANALYZE` to see how PostgreSQL executes a query and whether it uses indexes:

<!-- ZH -->
使用 `EXPLAIN ANALYZE` 查看 PostgreSQL 如何执行查询以及是否使用了索引：

<!-- EN -->
```sql
EXPLAIN ANALYZE SELECT * FROM "user" WHERE "firstName" = 'Timber';
```

<!-- ZH -->
```sql
EXPLAIN ANALYZE SELECT * FROM "user" WHERE "firstName" = 'Timber';
```

<!-- EN -->
Look for `Seq Scan` (full table scan — no index used) vs `Index Scan` or `Index Only Scan` (index used).

<!-- ZH -->
留意 `Seq Scan`（全表扫描——未使用索引）与 `Index Scan` 或 `Index Only Scan`（使用了索引）的区别。

<!-- EN -->
Aurora PostgreSQL

<!-- ZH -->
Aurora PostgreSQL

<!-- EN -->
This also applies to Amazon Aurora PostgreSQL, which uses the same query engine and EXPLAIN syntax. Aurora also offers [query plan management](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Optimize.html) for capturing and controlling execution plans.

<!-- ZH -->
这同样适用于 Amazon Aurora PostgreSQL，它使用相同的查询引擎和 EXPLAIN 语法。Aurora 还提供[查询计划管理](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Optimize.html)，用于捕获和控制执行计划。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Indexes](https://www.postgresql.org/docs/current/indexes.html)
* [EXPLAIN](https://www.postgresql.org/docs/current/sql-explain.html)
* [Using EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html)

<!-- ZH -->
* [Indexes](https://www.postgresql.org/docs/current/indexes.html)
* [EXPLAIN](https://www.postgresql.org/docs/current/sql-explain.html)
* [Using EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html)

<!-- EN -->
### SAP HANA

<!-- ZH -->
### SAP HANA

<!-- EN -->
Use `EXPLAIN PLAN FOR` to inspect the execution plan:

<!-- ZH -->
使用 `EXPLAIN PLAN FOR` 查看执行计划：

<!-- EN -->
```sql
EXPLAIN PLAN FOR SELECT * FROM "user" WHERE "firstName" = 'Timber';
SELECT * FROM EXPLAIN_PLAN_TABLE;
```

<!-- ZH -->
```sql
EXPLAIN PLAN FOR SELECT * FROM "user" WHERE "firstName" = 'Timber';
SELECT * FROM EXPLAIN_PLAN_TABLE;
```

<!-- EN -->
Look for `TABLE SCAN` (no index) vs `INDEX SCAN` or `INDEX SEEK` in the operator column.

<!-- ZH -->
在 operator 列中留意 `TABLE SCAN`（无索引）与 `INDEX SCAN` 或 `INDEX SEEK` 的区别。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Indexes](https://help.sap.com/docs/hana-cloud-database/sap-hana-cloud-sap-hana-database-sql-reference-guide/indexes)
* [EXPLAIN PLAN](https://help.sap.com/docs/hana-cloud-database/sap-hana-cloud-sap-hana-database-sql-reference-guide/explain-plan-statement-data-manipulation)

<!-- ZH -->
* [Indexes](https://help.sap.com/docs/hana-cloud-database/sap-hana-cloud-sap-hana-database-sql-reference-guide/indexes)
* [EXPLAIN PLAN](https://help.sap.com/docs/hana-cloud-database/sap-hana-cloud-sap-hana-database-sql-reference-guide/explain-plan-statement-data-manipulation)

<!-- EN -->
### SQLite

<!-- ZH -->
### SQLite

<!-- EN -->
Use `EXPLAIN QUERY PLAN` to see how SQLite resolves a query:

<!-- ZH -->
使用 `EXPLAIN QUERY PLAN` 查看 SQLite 如何解析查询：

<!-- EN -->
```sql
EXPLAIN QUERY PLAN SELECT * FROM user WHERE firstName = 'Timber';
```

<!-- ZH -->
```sql
EXPLAIN QUERY PLAN SELECT * FROM user WHERE firstName = 'Timber';
```

<!-- EN -->
Look for `SCAN` (no index) vs `SEARCH` (index used) in the output.

<!-- ZH -->
在输出中留意 `SCAN`（无索引）与 `SEARCH`（使用了索引）的区别。

<!-- EN -->
Learn more

<!-- ZH -->
进一步了解

<!-- EN -->
* [Query Planning](https://www.sqlite.org/queryplanner.html)
* [EXPLAIN QUERY PLAN](https://www.sqlite.org/eqp.html)

<!-- ZH -->
* [Query Planning](https://www.sqlite.org/queryplanner.html)
* [EXPLAIN QUERY PLAN](https://www.sqlite.org/eqp.html)

<!-- EN -->
## Defining indexes in TypeORM

<!-- ZH -->
## 在 TypeORM 中定义索引

<!-- EN -->
TypeORM supports creating indexes on table columns using the `@Index` decorator.

<!-- ZH -->
TypeORM 支持用 `@Index` 装饰器在表列上创建索引。

<!-- EN -->
* Basic index
* Composite index
* Join column

<!-- ZH -->
* 基础索引
* 复合索引
* 连接列

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, Index } from "typeorm"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    @Index()
    email: string

    @Column()
    firstName: string
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, Index } from "typeorm"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    @Index()
    email: string

    @Column()
    firstName: string
}
```

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, Index } from "typeorm"

@Entity()
@Index(["lastName", "firstName"]) // most selective column first
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, Index } from "typeorm"

@Entity()
@Index(["lastName", "firstName"]) // 选择性最高的列放最前
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- EN -->
```typescript
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToOne,
    Index,
} from "typeorm"
import { User } from "./User"

@Entity()
export class Post {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @ManyToOne(() => User)
    @Index() // index foreign key columns to speed up joins
    author: User
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToOne,
    Index,
} from "typeorm"
import { User } from "./User"

@Entity()
export class Post {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @ManyToOne(() => User)
    @Index() // 给外键列建索引以加速连接
    author: User
}
```

<!-- EN -->
For a comprehensive overview of different index types (unique, spatial, fulltext, concurrent, and more), read the [Indexes](https://typeorm.io/docs/indexes) guide.

<!-- ZH -->
要全面了解各种索引类型（唯一、空间、全文、并发等），请阅读[索引](https://typeorm.io/docs/indexes)指南。

<!-- EN -->
Proper indexing is often the single biggest performance improvement you can make — start by analyzing your slowest queries with the execution plan tools above, then add indexes where they matter most.

<!-- ZH -->
合理的索引往往是你能做出的最大单项性能改进——先用上面的执行计划工具分析最慢的查询，然后在最关键的地方加上索引。
