如何在 MikroORM 中为文本字段创建 tsvector 列以支持全文搜索?
解读
国内后端面试中,PostgreSQL 全文检索(GIN + tsvector)几乎是“高并发搜索”场景的标配。面试官抛出此题,并不是想听你背文档,而是考察三件事:
- 是否知道 MikroORM 的“元数据扩展”机制(@Property、columnType、expression 三把斧);
- 能否把 PostgreSQL 的 tsvector 生成规则(to_tsvector、language、coalesce)无缝落到实体层;
- 是否具备“可维护性”意识:迁移脚本、索引、查询封装、同步更新策略,一步不能少。
答不到“迁移脚本怎么写”“索引怎么挂”“查询怎么用”,就会被追问“那线上数据怎么更新?”——直接掉分。
知识点
- columnType:绕过 MikroORM 内置类型映射,直接写原生 DDL。
- expression:让 ORM 在 INSERT/UPDATE 时把计算逻辑下推到数据库,避免二次 UPDATE。
- GIN 索引:必须显式在迁移里创建,否则 tsvector 列无加速效果。
- 查询封装:使用 raw SQL + 参数化,防止 SQL 注入;同时利用 queryBuilder 的“类型穿透”保持链式调用。
- 同步策略:expression 列默认不可手动写入,需用“触发器”或“generated always as”保证一致性;MikroORM 的 knex 迁移支持
knex.raw,可一次到位。
答案
步骤一:实体定义——声明 tsvector 列
@Entity({ tableName: 'article' })
export class Article {
@PrimaryKey()
id!: number;
@Property()
title!: string;
@Property({ type: 'text' })
content!: string;
// 关键:columnType 写原生 DDL,expression 让 PG 自动维护
@Property({
columnType: 'tsvector',
expression: `to_tsvector('simple', coalesce(title,'') || ' ' || coalesce(content,''))`,
persist: false, // 禁止应用层写入
})
searchVector!: string; // 仅用于查询,类型写 string 即可
}
步骤二:迁移脚本——挂 GIN 索引
export class Migration20240601000000 extends Migration {
async up(): Promise<void> {
this.addSql(`
CREATE INDEX idx_article_search
ON "article"
USING GIN (to_tsvector('simple', coalesce(title,'') || ' ' || coalesce(content,'')));
`);
}
async down(): Promise<void> {
this.addSql(`DROP INDEX IF EXISTS idx_article_search;`);
}
}
步骤三:执行迁移
npx mikro-orm migration:create
npx mikro-orm migration:up
步骤四:类型安全查询——封装为 Repository 方法
export class ArticleRepository extends EntityRepository<Article> {
async search(keyword: string, limit = 20): Promise<Article[]> {
const knex = this.getKnex();
// 使用 plainToInstance 保持类型
const rawIds = await knex('article')
.select('id')
.where(
knex.raw(`search_vector @@ plainto_tsquery('simple', ?)`, [keyword])
)
.orderByRaw(
`ts_rank(search_vector, plainto_tsquery('simple', ?)) DESC`,
[keyword]
)
.limit(limit);
const ids = rawIds.map((r) => r.id);
return ids.length ? this.find({ id: { $in: ids } }) : [];
}
}
至此,tsvector 列已随表结构自动维护,GIN 索引生效,查询方法类型安全,可直接用于生产。
拓展思考
- 多语言场景:'simple' 字典无法满足中文分词,可改用 pg_jieba 或 zhparser;此时需在服务器端预装扩展,并在 expression 里指定
to_tsvector('jiebacfg', ...),迁移脚本里先执行CREATE EXTENSION IF NOT EXISTS pg_jieba;。 - 权重排序:标题权重高于内容,可在 expression 里用
setweight分段标记,查询时用ts_rank_cd('{0.1, 0.2, 0.4, 1.0}', search_vector, query)调整。 - 增量更新:如果 title/content 极少变更,可用物化列 + 触发器;若变更频繁,直接 expression 最省维护。MikroORM 目前不支持 PostgreSQL 的
GENERATED ALWAYS STORED语法,但用 expression 等效。 - 横向扩展:数据量过亿,单表 GIN 索引膨胀明显,可拆分区表,或把 tsvector 列同步到 ElasticSearch,MikroORM 侧仅做轻量检索,复杂搜索走 ES。
- 安全:keyword 必须参数化,禁止字符串拼接;同时给 searchVector 字段加
@Hidden(),防止意外序列化到前端。