索引与唯一约束
MikroORM 为在实体上定义索引与唯一约束提供了全面的支持。本指南涵盖从基础用法到数据库专属高级特性的全部内容。
基础索引与唯一约束定义
索引可以用 @Index() 装饰器定义,唯一约束用 @Unique() 定义。两者都可以应用在实体级(用于复合索引)或属性级(用于单列索引)。
@Entity()
@Index({ properties: ['name', 'age'] }) // 复合索引
@Index({ name: 'custom_idx_name', properties: ['name'] }) // 具名索引
@Unique({ properties: ['name', 'email'] }) // 复合唯一约束
export class Author {
@PrimaryKey()
id!: number;
@Property()
@Index() // 使用生成名称的简单索引
name!: string;
@Property()
@Unique() // 简单唯一约束
email!: string;
@Property()
@Index({ name: 'age_idx' }) // 具名索引
age?: number;
}@Entity()
@Index({ properties: ['name', 'age'] })
@Index({ name: 'custom_idx_name', properties: ['name'] })
@Unique({ properties: ['name', 'email'] })
export class Author {
@PrimaryKey()
id!: number;
@Property()
@Index()
name!: string;
@Property()
@Unique()
email!: string;
@Property()
@Index({ name: 'age_idx' })
age?: number;
}自定义索引表达式
对于需要自定义 SQL 的复杂索引,可以使用 expression 选项。它允许你指定确切的 CREATE INDEX 语句。
@Entity()
export class Author {
// 原始 SQL 表达式
@Index({
name: 'custom_index_expr',
expression: 'alter table `author` add index `custom_index_expr`(`title`)'
})
@Property()
title!: string;
// 带列与表引用的表达式回调
@Index({
name: 'custom_index_country',
expression: (columns, table, indexName) =>
`create index \`${indexName}\` on \`${table.name}\` (\`${columns.country}\`)`
})
@Property()
country!: string;
}部分索引
部分索引(也称过滤索引)只索引满足某个谓词的行。它们适合对行的一个子集强制唯一性,或加速针对特定数据切片的查询,同时保持索引体积很小。
在 @Index 或 @Unique 上使用 where 选项。可移植的形式是 FilterQuery 对象 —— 与你在 em.find() 中使用的运算符相同 —— 它在所有驱动上都可用。MikroORM 会把它渲染成 PostgreSQL / SQLite / MSSQL / MySQL / Oracle 上各方言的 SQL,在 MongoDB 上则渲染为 partialFilterExpression。
import { defineEntity, p } from '@mikro-orm/core';
const UserSchema = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
email: p.string(),
deletedAt: p.datetime().nullable(),
},
uniques: [
{ properties: ['email'], where: { deletedAt: null } },
],
});
export class User extends UserSchema.class {}
UserSchema.setClass(User);import { type InferEntity, defineEntity, p } from '@mikro-orm/core';
export const User = defineEntity({
name: 'User',
properties: {
id: p.integer().primary(),
email: p.string(),
deletedAt: p.datetime().nullable(),
},
uniques: [
{ properties: ['email'], where: { deletedAt: null } },
],
});
export type IUser = InferEntity<typeof User>;@Entity()
@Unique({ properties: ['email'], where: { deletedAt: null } })
export class User {
@PrimaryKey()
id!: number;
@Property()
email!: string;
@Property({ nullable: true })
deletedAt?: Date;
}@Entity()
@Unique({ properties: ['email'], where: { deletedAt: null } })
export class User {
@PrimaryKey()
id!: number;
@Property()
email!: string;
@Property({ nullable: true })
deletedAt?: Date;
}SQL 驱动也接受把原始 SQL 片段作为 where —— 这对那些不符合 FilterQuery 形态的谓词很有用(自定义运算符、函数调用、方言专属语法)。引号需要你自己负责:
const UserSchema = defineEntity({
name: 'User',
properties: { /* ... */ },
uniques: [
{ properties: ['email'], where: 'lower("email") <> \'\'' },
],
});export const User = defineEntity({
name: 'User',
properties: { /* ... */ },
uniques: [
{ properties: ['email'], where: 'lower("email") <> \'\'' },
],
});@Entity()
@Unique({ properties: ['email'], where: 'lower("email") <> \'\'' })
export class User { /* ... */ }@Entity()
@Unique({ properties: ['email'], where: 'lower("email") <> \'\'' })
export class User { /* ... */ }原始片段仅适用于 SQL —— MongoDB 会拒绝它们。
各方言生成的 DDL(对于 where: '"deleted_at" is null'):
| 方言 | 输出 |
|---|---|
| PostgreSQL | create unique index "user_email_uniq" on "user" ("email") where "deleted_at" is null |
| SQLite | create unique index \user_email_uniq` on `user` (`email`) where "deleted_at" is null` |
| MSSQL | create unique index [user_email_uniq] on [user] ([email]) where "deleted_at" is null |
| MySQL | alter table \user` add unique `user_email_uniq` ((case when "deleted_at" is null then `email` end))` |
| MariaDB | 不支持 —— 见下方说明 |
| Oracle | create unique index "user_email_uniq" on "user" ((case when "deleted_at" is null then "email" end)) |
| MongoDB | db.user.createIndex({ email: 1 }, { unique: true, partialFilterExpression: { deletedAt: null } }) |
MySQL / Oracle 如何模拟:这些引擎的索引没有原生 WHERE 子句,因此 MikroORM 会生成一个基于函数的索引,把每一列包进 (CASE WHEN <predicate> THEN <col> END)。谓词为假的行在索引表达式上得到 NULL,而由于在唯一索引中 NULL 被视为互不相同,唯一性就只在谓词成立的地方被强制。非唯一的部分索引也能通过同样的技巧工作(谓词外的行仍会被索引,只是键为 NULL)。
MariaDB:不支持内联表达式索引。如果你在 MariaDB 上需要部分索引,请定义一个把谓词烘焙进去的虚拟生成列,并在该列上创建常规索引。如果你尝试在 MariaDB 上使用 where,MikroORM 会抛出清晰的错误。
数据库支持情况:
| 形式 | 原生 | 模拟(CASE WHEN) | 不支持 |
|---|---|---|---|
对象 where(FilterQuery) | PostgreSQL、SQLite、MSSQL、MongoDB | MySQL 8.0.13+、Oracle | MariaDB(改用虚拟列) |
原始 SQL 字符串 where | PostgreSQL、SQLite、MSSQL | MySQL 8.0.13+、Oracle | MariaDB、MongoDB |
MySQL 的模拟方式(函数键部分索引)需要 MySQL 8.0.13 或更高版本。MikroORM 在生成 DDL 之前不会探测服务器版本 —— 更旧的 MySQL 服务器会在 schema 应用阶段用它自己的解析器错误拒绝该 CASE WHEN 表达式,而不是给出 MikroORM 专属的提示。
部分索引的 schema diff 会结构化地比较 WHERE 谓词 —— 用于检查约束的同一套表达式归一化器(折叠空白 / 引号 / 大小写)会应用到两端。修改或移除 where 会产生恰当的 ALTER/DROP+CREATE,重复执行 schema:update 不会产生 diff。
在 MySQL / MariaDB / Oracle 上,高级的 columns 选项(排序方向、前缀长度、排序规则)不能与 where 一起使用,因为那里每个索引列都会被包进 CASE WHEN 表达式。在这些驱动上请对部分索引使用 properties(或简单的 columnNames)。
expression 逃生舱(整个索引体的原始 SQL)不能与 where 组合 —— 这两种写谓词的方式互斥。如果你同时需要自定义表达式与谓词,请自行把 WHERE 子句内联进 expression。两者都设置时 MikroORM 会抛出清晰的错误。
在 PostgreSQL 上,基于函数列的索引(例如 lower(email)、(data->>'kind'))会被自省为不透明的 expression 字符串 —— 完整的 CREATE INDEX … WHERE … 能在往返中保留下来,但重新生成的实体会使用 expression 而非结构化的 properties + where。纯列的部分索引会以结构化 where 的形式往返。
通过 defineEntity({ extends }) 继承属性
where 谓词会针对实体的完整属性集合解析,因此子实体可以引用来自基类的属性 —— 这对复用 deletedAt 列或层级中的其他判别符很有用:
import { defineEntity, p } from '@mikro-orm/core';
export const SoftDeleteBase = defineEntity({
name: 'SoftDeleteBase',
abstract: true,
properties: {
id: p.integer().primary(),
deletedAt: p.datetime().nullable(),
},
});import { defineEntity, p } from '@mikro-orm/core';
import { SoftDeleteBase } from './SoftDeleteBase';
export const UserSchema = defineEntity({
extends: SoftDeleteBase,
name: 'User',
properties: {
email: p.string(),
},
uniques: [
// `deletedAt` 继承自 SoftDeleteBase
{ properties: ['email'], where: { deletedAt: null } },
],
});
export class User extends UserSchema.class {}
UserSchema.setClass(User);索引类型
你可以用 type 选项指定索引类型。这对全文索引、空间索引,或 hash、btree 这类数据库专属索引类型尤其有用。
// 全文索引(MySQL、PostgreSQL、MongoDB)
@Index({ properties: ['content'], type: 'fulltext' })
// 空间索引
@Index({ properties: ['location'], type: 'spatial' })
// 哈希索引(PostgreSQL)
@Index({ properties: ['lookup_key'], type: 'hash' })列排序方向与 NULLS 排序
你可以使用 columns 选项为索引中的每一列指定排序方向(ASC/DESC)与 null 排序(NULLS FIRST/NULLS LAST)。
@Entity()
@Index({
properties: ['createdAt', 'name'],
columns: [
{ name: 'createdAt', sort: 'DESC', nulls: 'LAST' },
{ name: 'name', sort: 'ASC' },
],
})
export class Article {
@PrimaryKey()
id!: number;
@Property()
name!: string;
@Property()
createdAt!: Date;
}数据库支持情况:
- 排序方向:MySQL、MariaDB、PostgreSQL、MSSQL、SQLite
- NULLS FIRST/LAST:仅 PostgreSQL
列前缀长度
对于文本列,你可以用 length 选项只为前 N 个字符创建索引。这对索引大文本字段很有用。
@Entity()
@Index({
properties: ['content'],
columns: [{ name: 'content', length: 100 }],
})
export class Article {
@PrimaryKey()
id!: number;
@Property({ type: 'text' })
content!: string;
}数据库支持情况: MySQL、MariaDB
列排序规则
你可以为索引列指定排序规则,它会影响索引内部字符串比较的方式。
@Entity()
@Index({
properties: ['name'],
columns: [{ name: 'name', collation: 'C' }],
})
export class User {
@PrimaryKey()
id!: number;
@Property()
name!: string;
}数据库支持情况: PostgreSQL、SQLite、MySQL、MariaDB
覆盖索引(INCLUDE 列)
覆盖索引会把额外的列存储在索引叶子页中,使查询可以完全由索引满足而无需访问表数据。
@Entity()
@Index({
properties: ['email'],
include: ['name', 'createdAt'], // 这些列会被存入索引
})
export class User {
@PrimaryKey()
id!: number;
@Property()
email!: string;
@Property()
name!: string;
@Property()
createdAt!: Date;
}这会生成类似如下的 SQL:
-- PostgreSQL
CREATE INDEX user_email_idx ON "user" ("email") INCLUDE ("name", "created_at")
-- MSSQL
CREATE INDEX [user_email_idx] ON [user] ([email]) INCLUDE ([name], [created_at])数据库支持情况: PostgreSQL、MSSQL
填充因子
填充因子指定每个索引页中用数据填充的空间百分比,其余留作空闲空间供后续增长。
@Entity()
@Index({
properties: ['email'],
fillFactor: 70, // 填充 70%,30% 空闲
})
export class User {
@PrimaryKey()
id!: number;
@Property()
email!: string;
}数据库支持情况: PostgreSQL、MSSQL
不可见/隐藏索引
不可见索引由数据库维护(写入时更新),但不会被查询优化器使用。这在真正删除索引之前测试其影响时很有用。
@Entity()
@Index({
properties: ['name'],
invisible: true,
})
export class User {
@PrimaryKey()
id!: number;
@Property()
name!: string;
}数据库支持情况: MySQL 8.0+、MariaDB 10.6+、MongoDB
禁用索引
禁用的索引既不会被查询优化器使用,也不会在写入时维护。这与不可见索引不同 —— 后者仍会被维护。禁用的索引可以稍后用 ALTER INDEX ... REBUILD 重新启用。
@Entity()
@Index({
properties: ['name'],
disabled: true,
})
export class User {
@PrimaryKey()
id!: number;
@Property()
name!: string;
}数据库支持情况: MSSQL
聚集索引
聚集索引决定表中数据的物理顺序。每张表只能存在一个聚集索引。
@Entity()
@Index({
properties: ['createdAt'],
clustered: true,
})
export class Event {
@PrimaryKey()
id!: number;
@Property()
createdAt!: Date;
}数据库支持情况: MariaDB(仅 Aria 存储引擎)、MSSQL
在 MariaDB 中,聚集索引(CLUSTERING=YES)只对 Aria 存储引擎生效。对 InnoDB 表使用该选项不会有任何效果(该选项会被静默忽略)。
可延迟唯一约束(PostgreSQL)
PostgreSQL 支持可延迟约束,它们可以在事务结束时而非立即被检查。
@Entity()
@Unique({
properties: ['email'],
deferMode: 'INITIALLY_DEFERRED', // 或 'INITIALLY_IMMEDIATE'
})
export class User {
@PrimaryKey()
id!: number;
@Property()
email!: string;
}数据库支持情况: PostgreSQL
JSON 列索引
MikroORM 会自动处理 JSON 列的索引。当你指定的属性路径包含 JSON 列时,会生成相应的表达式索引。
@Entity()
@Index({ properties: ['metadata.email'] }) // 索引 JSON 内的某个字段
export class User {
@PrimaryKey()
id!: number;
@Property({ type: 'json' })
metadata!: { email: string; phone: string };
}组合多个选项
你可以把多个索引选项组合起来:
@Entity()
@Index({
name: 'user_search_idx',
properties: ['lastName', 'firstName'],
columns: [
{ name: 'lastName', sort: 'ASC' },
{ name: 'firstName', sort: 'ASC' },
],
include: ['email', 'phone'],
fillFactor: 80,
})
export class User {
@PrimaryKey()
id!: number;
@Property()
firstName!: string;
@Property()
lastName!: string;
@Property()
email!: string;
@Property()
phone!: string;
}数据库支持总览
| 特性 | MySQL | MariaDB | PostgreSQL | PGlite | CockroachDB | MSSQL | Oracle | SQLite | libSQL | MongoDB |
|---|---|---|---|---|---|---|---|---|---|---|
| 基础索引 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| 唯一约束 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| 复合索引 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| 索引表达式 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | - |
部分索引(where) | ✅ (CASE WHEN) | - | ✅ | ✅ | ✅ | ✅ | ✅ (CASE WHEN) | ✅ | ✅ | ✅ (对象形式 → partialFilterExpression) |
| 全文索引 | ✅ | ✅ | ✅ | ✅ | - | ✅ | - | - | - | ✅ |
| 排序方向(ASC/DESC) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | - |
| NULLS FIRST/LAST | - | - | ✅ | ✅ | ✅ | - | ✅ | - | - | - |
| 列前缀长度 | ✅ | ✅ | - | - | - | - | - | - | - | - |
| 排序规则 | ✅ | ✅ | ✅ | ✅ | ✅ | - | ✅ | ✅ | ✅ | - |
| INCLUDE 列 | - | - | ✅ | ✅ | ✅ | ✅ | - | - | - | - |
| 填充因子 | - | - | ✅ | ✅ | - | ✅ | - | - | - | - |
| 不可见索引 | ✅ | ✅ | - | - | - | - | - | - | - | ✅ |
| 禁用索引 | - | - | - | - | - | ✅ | - | - | - | - |
| 聚集索引 | - | ✅ | - | - | - | ✅ | - | - | - | - |
| 可延迟约束 | - | - | ✅ | ✅ | - | - | ✅ | - | - | - |
查询时索引提示(using)
FindOptions 上的 using 选项让你可以告诉数据库某个查询应使用哪个具名索引,并且自带校验。它是原始 indexHint 选项的高层配套 —— 你不必手写方言专属的提示语法,只需传入实体上已声明索引的名称,MikroORM 会:
- 校验该索引确实存在于实体上。
- 校验
where/orderBy中用到的每个属性都被该索引覆盖。 - 为底层驱动生成相应的 SQL 提示。
const users = await em.find(User, { name: 'foo' }, {
using: 'idx_user_name',
});
// 也接受数组 —— where/orderBy 可以使用它们所覆盖属性的并集
em.find(User, { name: 'foo', email: 'bar@x' }, {
using: ['idx_user_name', 'uniq_user_email'],
});各驱动行为:
| 驱动 | 生成的提示 |
|---|---|
| MySQL / MariaDB | USE INDEX (idx_name[, ...]) |
| MSSQL | WITH (INDEX(idx_name[, ...])) |
| MongoDB | 作为 hint 选项传入(仅单个索引) |
| PostgreSQL | 仅校验 —— 无原生提示语法 |
| SQLite / libSQL | 仅校验 |
当 using 与 indexHint 都设置时,原始 indexHint 生效并原样输出;using 仍会校验 where / orderBy。
类型安全的 using
要让 using 能够自动补全索引名,并把 where 收窄为只包含所选索引覆盖的属性,实体必须声明一个索引映射。不同定义方式的机制有所不同:
defineEntity —— 自动推断
通过属性级 .index('name') / .unique('name') 以及实体级 indexes / uniques 数组声明的具名索引会被自动识别。无需额外声明:
import { defineEntity, p } from '@mikro-orm/core';
const Article = defineEntity({
name: 'Article',
properties: {
id: p.integer().primary(),
title: p.string().index('idx_article_title'),
slug: p.string().unique('uniq_article_slug'),
status: p.string(),
views: p.integer(),
},
indexes: [{ name: 'idx_article_status_views', properties: ['status', 'views'] }],
});
em.find(Article, { title: 'foo' }, { using: 'idx_article_title' });
em.find(Article, { slug: 'foo' }, { using: 'uniq_article_slug' });
em.find(Article, { status: 'draft', views: 100 }, { using: 'idx_article_status_views' });
// @ts-expect-error 'views' 不被 'idx_article_title' 覆盖
em.find(Article, { views: 100 }, { using: 'idx_article_title' });装饰器实体 —— [IndexHints] 符号
装饰器元数据不会把索引名带入实体类型,因此你需要用 IndexHints 符号把索引映射写成一个幻影属性(与 [PrimaryKeyProp] 或 [OptionalProps] 是同一套路):
import { Entity, Index, PrimaryKey, Property, Unique } from '@mikro-orm/decorators/legacy';
import { IndexHints, PrimaryKeyProp } from '@mikro-orm/core';
@Entity()
@Index({ name: 'idx_user_name', properties: ['name'] })
@Index({ name: 'idx_user_name_email', properties: ['name', 'email'] })
@Unique({ name: 'uniq_user_email', properties: ['email'] })
class User {
[PrimaryKeyProp]?: 'id';
[IndexHints]?: {
idx_user_name: 'name';
idx_user_name_email: 'name' | 'email';
uniq_user_email: 'email';
};
@PrimaryKey()
id!: number;
@Property()
name!: string;
@Property()
email!: string;
@Property({ nullable: true })
age?: number;
}
em.find(User, { name: 'foo' }, { using: 'idx_user_name' });
// @ts-expect-error 'age' 不在 idx_user_name 中
em.find(User, { age: 30 }, { using: 'idx_user_name' });幻影 [IndexHints]? 声明是纯类型的 —— 它在运行时不存在,也永远不会被序列化。每个键是一个索引名;每个值是该索引覆盖的属性名联合。当未声明 [IndexHints] 时,using 会回退为 string 并接受任意名称(运行时校验仍然生效)。
运行时校验
即便类型系统没有捕捉到错误(例如没有 [IndexHints] 的实体,或 where 被强制转换为 any 时),校验依然会执行:
// 抛出:Index 'nonexistent_idx' not found on entity 'User'. Available indexes: ...
em.find(User, { name: 'foo' }, { using: 'nonexistent_idx' });
// 抛出:Property 'age' in where clause is not covered by index 'idx_user_name'
em.find(User, { age: 30 } as any, { using: 'idx_user_name' });
// 抛出:Property 'age' in orderBy is not covered by index 'idx_user_name'
em.find(User, { name: 'foo' }, { using: 'idx_user_name', orderBy: { age: 'asc' } });校验器会递归遍历 $and / $or / $not,因此嵌套条件同样会被检查。属性值内部的非属性运算符(例如 { name: { $eq: 'foo' } })只要外层属性被覆盖就会被接受。
对应的 FindOptions 参考请参见实体管理器页面上的索引提示与通过 using 指定具名索引提示。
另见
- 定义实体 —— 实体定义通用指南
- Schema 生成器 —— 索引如何在数据库中被创建
- 迁移 —— 管理包括索引在内的 schema 变更