Indexes & Uniques
Sequelize supports adding indexes to the model definition which will be created during model synchronization. You have multiple ways of defining indexes on a model.
Single-column index
The @Index
decorator is the simplest solution to define an index. It is ideal for single-column indexes.
To define an index, you use the @Index
decorator on the attribute you want to index:
import { Model, DataTypes } from '@sequelize/core';
import { Index, Attribute, NotNull } from '@sequelize/core/decorators-legacy';
class User extends Model {
@Attribute(DataTypes.STRING)
@NotNull
@Index
declare firstName: string;
}
The @Index
decorator accepts an optional options bag as a parameter.
The list of available options is available in the API documentation.
Here is an example of a single-column gin index:
import { Model, DataTypes } from '@sequelize/core';
import { Index, Attribute, NotNull } from '@sequelize/core/decorators-legacy';
class User extends Model {
@Attribute(DataTypes.JSONB)
@NotNull
@Index({ using: 'gin' })
declare data: object;
}
Index names are automatically generated by Sequelize, but you can also specify a custom index name using the name
option:
import { Model, DataTypes } from '@sequelize/core';
import { Index, Attribute, NotNull } from '@sequelize/core/decorators-legacy';
class User extends Model {
@Attribute(DataTypes.STRING)
@NotNull
@Index({ name: 'user_first_name_index' })
declare firstName: string;
}