You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeORM的Entity Schema文件中为列创建索引?

使用TypeORM Entity Schema为列创建索引

你可以通过两种方式在Entity Schema中为列添加索引,对应装饰器@Index()的效果:

方式一:列级别快捷配置

直接在列的定义里添加index: true,适合单列的基础索引:

import { EntitySchema } from "typeorm";

export const FooSchema = new EntitySchema({
    name: "Foo",
    columns: {
        toBeIndexed: {
            type: String,
            index: true // 开启该列的索引
        }
    }
});

方式二:全局索引配置(支持复杂场景)

如果需要自定义索引名称、创建联合索引或者唯一索引,在Entity Schema的indices数组中配置:

import { EntitySchema } from "typeorm";

export const FooSchema = new EntitySchema({
    name: "Foo",
    columns: {
        toBeIndexed: {
            type: String
        },
        anotherColumn: {
            type: Number
        }
    },
    indices: [
        // 单列自定义索引
        {
            name: "foo_to_be_indexed_idx", // 可选自定义索引名称
            columns: ["toBeIndexed"]
        },
        // 多列联合索引
        {
            columns: ["toBeIndexed", "anotherColumn"]
        },
        // 唯一索引
        {
            columns: ["toBeIndexed"],
            unique: true
        }
    ]
});

两种方式都能实现和装饰器@Index()一致的效果,按需选择即可。

内容的提问来源于stack exchange,提问作者user1870238

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 17:52:46