According to the documentation and the comments in the sqlalchemy.Column
class, we should use the class sqlalchemy.schema.Index
to specify an index that contains multiple columns.
However, the example shows how to do it by directly using the Table object like this:
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)
How should we do it if we use the declarative ORM extension?
class A(Base):
__tablename__ = 'table_A'
id = Column(Integer, , primary_key=True)
a = Column(String(32))
b = Column(String(32))
I would like an index on column "a" and "b".
those are just
Column
objects, index=True flag works normally:if you'd like a composite index, again
Table
is present here as usual you just don't have to declare it, everything works the same (make sure you're on recent 0.6 or 0.7 for the declarative A.a wrapper to be interpreted as aColumn
after the class declaration is complete):In 0.7 the
Index
can be in theTable
arguments too, which with declarative is via__table_args__
:To complete @zzzeek's answer.
If you like to add a composite index with DESC and use the ORM declarative method you can do as follows.
Furthermore, I was struggling with the Functional Indexes documentation of SQSAlchemy, trying to figure out a how to substitute
mytable.c.somecol
.We can just use the model property and call
.desc()
on it:If you use Alembic, I'm using Flask-Migrate, it generates something like:
Finally you should have the following table and indexes in your PostgreSQL database: