【问题标题】:Sequelize create index on JSONB attributeSequelize 在 JSONB 属性上创建索引
【发布时间】:2021-10-15 08:59:24
【问题描述】:

如何使用 sequelize 的语法为 postgres 中的 JSONB 字段创建索引?

我想在 SQL 中创建的索引是:

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

如何使用 sequelize 语法实现这一点? 我搜索了文档并在 Google 上搜索了示例,但结果为空白。

【问题讨论】:

  • 您可以在索引定义中提供Sequelize.fn,而不是字段名称。也许你可以使用Sequelize.fn("CAST", Sequelize.col("data")) 之类的东西。我不知道它的语法,所以我只是把它作为可能的提示。

标签: node.js postgresql sequelize.js jsonb


【解决方案1】:

您可以将其添加到您的模型定义中。

我在下面给出一个基本的例子:

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)")]
        }]
    }
);

【讨论】:

    【解决方案2】:

    我想不出更优雅的方式来做到这一点,最终使用了 afterSync 钩子:

            afterSync(options, done) {
                co(function* () {
                    yield sequelize.query(
                        'CREATE INDEX people ON people (cast(people.data->>\'id\' AS bigint));'
                    );
                })
                .then(() => done())
                .catch(err => done(err))
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-22
      • 2016-01-19
      • 2018-05-29
      • 2018-06-25
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      相关资源
      最近更新 更多