TypeORM - 索引
一般来说,索引是通过优化数据存储来优化数据库性能的过程。它用于快速定位和访问数据库中的数据。本节介绍如何在 TypeORM 中使用索引。索引分为不同类型。让我们逐一详细介绍。
列索引
我们可以使用 @Index 为特定列创建索引。考虑一个 Customer 实体的示例,如下所示,并为 firstName 列定义索引,
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; @Entity() export class Student { @PrimaryGeneratedColumn() id: number; @Index() @Column() firstName: string; @Column() lastName: string; @Column() age: number; @Column() address: string; }
@Index 允许为索引指定名称 −
@Index("Name-idx") @Column() firstName: string;
唯一索引
要在列中指定 Unique 约束,请使用以下属性 −
{ unique: true }
例如,以下是为 Name 列指定唯一索引的代码 −
@Index({ unique: true }) @Column() firstName: string;
要为多个列应用索引,我们可以在 @Entity() 之后直接指定它。示例代码如下 −
@Entity() @Index(["firstName", "lastName"]) @Index(["firstName", "lastName"], { unique: true })
空间索引
空间索引允许访问空间对象。MySQL 和 PostgreSQL 支持空间索引。要在列中启用空间索引,请添加以下属性 −
{ spatial: true }
空间类型有多个子类型,例如几何、点、线串、多边形等,例如,如果您想在列中添加点空间类型,请使用以下代码 −
@Column("point") @Index({ spatial: true }) point: string;
禁用同步
要禁用同步,请在 @Index 装饰器上使用以下选项 −
{ synchronize: false }