Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize create index on JSONB attribute

How do I create an index using sequelize's syntax for a JSONB field in postgres?

The index I want to create in SQL would be:

CREATE INDEX people ON people (cast(people.data->>'id' AS bigint));

How do achieve this with the sequelize syntax? I've searched the docs and googled for examples but come up blank.

like image 353
ChrisJ Avatar asked Jul 04 '26 08:07

ChrisJ


1 Answers

You can add it to your Model Definition.

I am giving a basic example below:

const Test = sequelize.define(
    'People',
    {
        data: {
            type: DataTypes.JSONB,
            allowNull: false,
            field: 'data',
        }
    },
    {
        tableName: 'people',
        timestamps: true,
        paranoid: true,
        indexes: [{
            name: 'people_data_id',
            fields: [Sequelize.literal("((\"data\"->>'id')::int)")]
        }]
    }
);
like image 130
Rajath R Avatar answered Jul 06 '26 01:07

Rajath R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!