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

yor*_*rjo 83 python database indexing orm sqlalchemy

根据文档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)
Run Code Online (Sandbox Code Playgroud)

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

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

我想要列"a"和"b"的索引.

zzz*_*eek 119

那些只是Column对象,index = True flag正常工作:

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

如果你想要一个复合索引,Table那么像往常一样在这里再次出现你只需要声明它,一切都是一样的(确保你在最近的0.6或0.7,声明的Aa包装器被解释为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)
Run Code Online (Sandbox Code Playgroud)

在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"), )
Run Code Online (Sandbox Code Playgroud)

  • 所以我想我可以做__table_args__ =(索引('my_index',"a","b"),{'mysql_engine':'InnoDB'}) (5认同)
  • 如果你有像我现在这样的table_args字典会怎么样?__table_args__ = {'mysql_engine':'InnoDB'} (4认同)
  • @RyanChou http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/table_config.html#table-configuration“可以通过将最后一个参数指定为字典来使用上述形式指定关键字参数” (4认同)
  • 谢谢,我更新到 0.7 并且使用 __table_args__ 工作正常 (2认同)

小智 7

完成@zzzeek的答案

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

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

from sqlalchemy import Index

Index('someindex', mytable.c.somecol.desc())
Run Code Online (Sandbox Code Playgroud)

我们可以使用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),
    )
Run Code Online (Sandbox Code Playgroud)

如果您使用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 ###
Run Code Online (Sandbox Code Playgroud)

最后,您应该在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)
Run Code Online (Sandbox Code Playgroud)

  • 我无法使用“Index”函数中的类属性 oO (2认同)