使用sqlalchemy的声明性ORM扩展时的多列索引


94

根据文档sqlalchemy.Column该类中的注释,我们应该使用该类sqlalchemy.schema.Index来指定包含多个列的索引。

但是,该示例显示了如何通过直接使用Table对象来实现此目的,如下所示:

meta = MetaData()
mytable = Table('mytable', meta,
    # an indexed column, with index "ix_mytable_col1"
    Column('col1', Integer, index=True),

    # a uniquely indexed column with index "ix_mytable_col2"
    Column('col2', Integer, index=True, unique=True),

    Column('col3', Integer),
    Column('col4', Integer),

    Column('col5', Integer),
    Column('col6', Integer),
    )

# place an index on col3, col4
Index('idx_col34', mytable.c.col3, mytable.c.col4)

如果使用声明性ORM扩展,应该怎么做?

class A(Base):
    __tablename__ = 'table_A'
    id = Column(Integer, , primary_key=True)
    a = Column(String(32))
    b = Column(String(32))

我想在“ a”和“ b”列上建立索引。


1
关于要在多个列上使用多个索引还是单个索引,这个问题尚不清楚(在我对其进行编辑之前更加困惑-最初它很高兴地询问“包含多个多重索引的索引”)。但无论如何,我想,因为zzzeek的答案解决了这两种情况。
Mark Amery

Answers:


137

这些只是Column对象,index = True标志正常工作:

class A(Base):
    __tablename__ = 'table_A'
    id = Column(Integer, primary_key=True)
    a = Column(String(32), index=True)
    b = Column(String(32), index=True)

如果您想要复合索引, Table照常出现在这里,就不必声明它,一切都一样(确保声明性Aa包装器被解释为a是最近的0.6或0.7)Column类声明完成后):

class A(Base):
    __tablename__ = 'table_A'
    id = Column(Integer, primary_key=True)
    a = Column(String(32))
    b = Column(String(32))

Index('my_index', A.a, A.b)

在0.7中,Index也可以在Table参数中,通过__table_args__以下方式进行声明:

class A(Base):
    __tablename__ = 'table_A'
    id = Column(Integer, primary_key=True)
    a = Column(String(32))
    b = Column(String(32))
    __table_args__ = (Index('my_index', "a", "b"), )

1
谢谢,我更新到0.7并使用table_args可以正常工作
yorjo 2011年

5
如果像我目前一样有一个table_args字典,会发生什么?table_args = {'mysql_engine':'InnoDB'}
Nick Holden


6
所以我想我可以做table_args =(Index('my_index',“ a”,“ b”),{'mysql_engine':'InnoDB'})
Nick Holden

1
@RyanChou docs.sqlalchemy.org/zh-CN/latest/orm/extensions/declarative / ... “可以通过上述形式通过将最后一个参数指定为字典来指定关键字参数”
zzzeek 2015年

12

完成@zzzeek的答案

如果要使用DESC添加复合索引并使用ORM声明性方法,则可以执行以下操作。

此外,我还在SQSAlchemy 的功能索引文档中苦苦挣扎,试图找出一种替代方法mytable.c.somecol

from sqlalchemy import Index

Index('someindex', mytable.c.somecol.desc())

我们可以使用model属性并对其进行调用.desc()

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class GpsReport(db.Model):
    __tablename__ = 'gps_report'

    id = db.Column(db.Integer, db.Sequence('gps_report_id_seq'), nullable=False, autoincrement=True, server_default=db.text("nextval('gps_report_id_seq'::regclass)"))

    timestamp = db.Column(db.DateTime, nullable=False, primary_key=True)

    device_id = db.Column(db.Integer, db.ForeignKey('device.id'), primary_key=True, autoincrement=False)
    device = db.relationship("Device", back_populates="gps_reports")


    # Indexes

    __table_args__ = (
        db.Index('gps_report_timestamp_device_id_idx', timestamp.desc(), device_id),
    )

如果您使用Alembic,那么我使用的是Flask-Migrate,它会生成如下内容:

from alembic import op  
import sqlalchemy as sa
# Added manually this import
from sqlalchemy.schema import Sequence, CreateSequence


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    # Manually added the Sequence creation
    op.execute(CreateSequence(Sequence('gps_report_id_seq')))

    op.create_table('gps_report',
    sa.Column('id', sa.Integer(), server_default=sa.text("nextval('gps_report_id_seq'::regclass)"), nullable=False),
    sa.Column('timestamp', sa.DateTime(), nullable=False))
    sa.Column('device_id', sa.Integer(), autoincrement=False, nullable=False),
    op.create_index('gps_report_timestamp_device_id_idx', 'gps_report', [sa.text('timestamp DESC'), 'device_id'], unique=False)


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index('gps_report_timestamp_device_id_idx', table_name='gps_report')
    op.drop_table('gps_report')

    # Manually added the Sequence removal
    op.execute(sa.schema.DropSequence(sa.Sequence('gps_report_id_seq'))) 
    # ### end Alembic commands ###

最后,您应该在PostgreSQL数据库中具有以下表和索引:

psql> \d gps_report;
                                           Table "public.gps_report"
     Column      |            Type             | Collation | Nullable |                Default                 
-----------------+-----------------------------+-----------+----------+----------------------------------------
 id              | integer                     |           | not null | nextval('gps_report_id_seq'::regclass)
 timestamp       | timestamp without time zone |           | not null | 
 device_id       | integer                     |           | not null | 
Indexes:
    "gps_report_pkey" PRIMARY KEY, btree ("timestamp", device_id)
    "gps_report_timestamp_device_id_idx" btree ("timestamp" DESC, device_id)
Foreign-key constraints:
    "gps_report_device_id_fkey" FOREIGN KEY (device_id) REFERENCES device(id)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.