Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an ordered Index in sqlite db using SQLAlchemy

I'm defining a table in SQLAlchemy using the declarative API. It's got a foreign key which I'd like to index. My question is: how do I define the index created from master_ref to be an ASC or DESC index (without resorting to doing it manually with SQL)?

class Item(Base):
    id = Column(INTEGER, primary_key=True)
    master_ref = Column(INTEGER, ForeignKey('master.id'), nullable=True, index=True)
    value = Column(REAL)

Looking at the documentation of SqlAlchemy, an alternative way to create the index would be:

class Item(Base):
    id = Column(INTEGER, primary_key=True)
    master_ref = Column(INTEGER, ForeignKey('master.id'))
    value = Column(REAL)
    Index('ix_name', master_ref)

but I cannot find any reference on how to define the ASC or DESC anywhere.

like image 781
John Go-Soco Avatar asked Apr 30 '19 13:04

John Go-Soco


People also ask

Can I use SQLAlchemy with SQLite?

The great thing about SQLAlchemy is that it supports all popular database systems, including SQLite3, MySQL, PostgreSQL, Oracle, Microsoft SQL Server, etc.

How do I index a column in SQLite?

1. Syntax. The CREATE INDEX command consists of the keywords "CREATE INDEX" followed by the name of the new index, the keyword "ON", the name of a previously created table that is to be indexed, and a parenthesized list of table column names and/or expressions that are used for the index key.

What is index in SQLAlchemy?

SQLAlchemy Index is used for assigning the identifiers for each of the particular row getting stored inside a table. We can have indexing based on the single column or collection of two or more columns together acting as an index to the table rows.

Does SQLite automatically create index?

Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints.


Video Answer


1 Answers

You can use a functional index, as specified in the documentation:

Functional Indexes

Index supports SQL and function expressions, as supported by the target backend. To create an index against a column using a descending value, the ColumnElement.desc() modifier may be used:

from sqlalchemy import Index

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

And likewise for an ascending value, use the ColumnElement.asc() modifier.

like image 199
Mark Benningfield Avatar answered Sep 30 '22 10:09

Mark Benningfield