16

是否可以通过 alembic 脚本为 DB 表创建并发索引?

我正在使用 postgres DB,并且能够在 postgres 提示符下通过 sql 命令创建并发表索引。(在 (); 上同时创建索引)

但是找不到通过 Db 迁移(alembic)脚本创建相同的方法。如果我们创建普通索引(非并发),它将锁定数据库表,因此无法并行执行任何查询。所以只想知道如何通过alembic(DB迁移)脚本创建并发索引

4

3 回答 3

13

Alembic 支持PostgreSQL同时创建索引

def upgrade():
    op.execute('COMMIT')
    op.create_index('ix_1', 't1', ['col1'], postgresql_concurrently=True)
于 2019-10-22T15:55:20.817 回答
2

我没有使用 Postgres,也无法对其进行测试,但应该可以。根据:

http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html

从 0.9.9 版开始,Postgres 方言允许并发索引。但是,像这样的迁移脚本应该适用于旧版本(直接创建 SQL):

from alembic import op, context
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import text

# ---------- COMMONS
# Base objects for SQL operations are:
#     - use op = INSERT, UPDATE, DELETE
#     - use connection = SELECT (and also INSERT, UPDATE, DELETE but this object has lot of logics)
metadata = MetaData()
connection = context.get_bind()

tbl = Table('test', metadata, Column('data', Integer), Column("unique_key", String))
# If you want to define a index on the current loaded schema:
# idx1 = Index('test_idx1', tbl.c.data, postgresql_concurrently=True)


def upgrade():
    ...
    queryc = \
    """
    CREATE INDEX CONCURRENTLY test_idx1 ON test (data, unique_key);
    """
    # it should be possible to create an index here (direct SQL):
    connection.execute(text(queryc))
    ...
于 2015-04-30T09:12:16.303 回答
-1

虽然 Postgresql 中允许并发索引,但 Alembic 不支持并发操作,一次只能运行一个进程。

于 2016-07-27T13:11:14.300 回答