【问题标题】:How to create a Postgres GIN index with a config using SQLAlchemy?如何使用 SQLAlchemy 创建带有配置的 Postgres GIN 索引?
【发布时间】:2019-11-11 05:08:32
【问题描述】:

我在 Postgres 表上手动创建了 GIN 索引,如下所示:

create index idx_ib_keywords on stuff using gin(to_tsvector('english'::regconfig, keywords));

它被创建得很好:

\d info_block_template
                 Table info_block_template
   Column   | Type   | Collation | Nullable | Default
------------+--------+-----------+----------+--------
.
.
.
 keywords   | text   |           | not null | 
.
.
.
Indexes:
    .
    .    "idx_ib_keywords" gin (to_tsvector('english'::regconfig, keywords))

现在,我正在使用 alembic 进行迁移。当我使用 alembic 自动生成迁移时,不会自动生成 GIN 索引。不用担心,自动生成器不应该是完美的。所以我想进去手工编辑迁移文件。

我已经搜索了如何做到这一点,我能找到的最接近的是this page,我关注并写道

op.create_index(op.f('idx_ib_keywords'), 'stuff', ['keywords'], postgresql_using='gin')

进入我的迁移脚本。当我应用此迁移时,我收到错误:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedObject) 数据类型文本没有访问方法“gin”的默认运算符类 提示:您必须为索引指定一个运算符类或为数据类型定义一个默认运算符类。

这是一个很好的错误信息;它告诉我我需要做to_tsvector 的事情。但是,我不知道如何在 SQLAlchemy 中做到这一点。

有没有一种简单的方法可以在 SQLAlchemy 中编写它,或者我应该在迁移文件中放入原始 SQL?

【问题讨论】:

    标签: postgresql sqlalchemy full-text-search alembic


    【解决方案1】:

    事实证明,附加信息被指定为功能索引,不是作为postgresql_using kwarg的一部分。

    正确的 SQLAlchemy 语句是:

    op.create_index(op.f('idx_ib_keywords'),
                    'info_block_template',
                    [sa.text('to_tsvector(\'english\'::regconfig, keywords)')],
                    postgresql_using='gin')
    

    应用此迁移时,新创建的索引将完全按照需要显示:

    "idx_ib_keywords" gin (to_tsvector('english'::regconfig, keywords))
    

    【讨论】:

      【解决方案2】:

      在您的解决方案的帮助下,我得到了这个工作。可能值得一提的是,'info_block_template' 是表名,在上面的示例中它是'stuff'。我不确定这是否是一些特殊的语法。

      它也适用于索引的 btree 查询。例如

      op.create_index(op.f('ix_index_name'), 'table_name',
                  [sa.text('(jsonb_column_name #>> \'{top_level_object,second_level}\')')])
      

      【讨论】:

      • 谢谢你,太真实了!我将问题固定为与答案一致。也很高兴了解 btree 查询。
      猜你喜欢
      • 2015-09-02
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 2023-03-19
      • 2020-05-12
      • 2016-09-20
      相关资源
      最近更新 更多