Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding indexes to SQLAlchemy models after table creation

I have a flask-sqlalchemy model:

class MyModel(db.Model): __tablename__ = 'targets' id = db.Column(db.Integer, primary_key=True) url = db.Column(db.String(2048)) 

The table has already been created, and is in use. I want to create an index on the url attribute, so I pass index=True to it:

url = db.Column(db.String(2048), index=True) 

How can I make this index take effect, without deleting and recreating the table?

like image 442
user964375 Avatar asked Jan 19 '13 21:01

user964375


People also ask

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.

What is the use of MetaData in SQLAlchemy?

It is used when reflecting and creating databases in Python (using SQLAlchemy package). MetaData is a container object that keeps together many different features of a database (or multiple databases) being described.

What does base MetaData Create_all do?

create_all() creates foreign key constraints between tables usually inline with the table definition itself, and for this reason it also generates the tables in order of their dependency.


1 Answers

Given the model class from the original question.

class MyModel(db.Model):     __tablename__ = 'targets'     id = db.Column(db.Integer, primary_key=True)     url = db.Column(db.String(2048)) 

You cannot just add index=True because even if you called db.Model.metadata.create_all() the index will not be created on an already created table.

Instead, you need to create an independent Index object, and then create it. It will look something like this:

class MyModel(db.Model):     __tablename__ = 'targets'     id = db.Column(db.Integer, primary_key=True)     url = db.Column(db.String(2048))  mymodel_url_index = Index('mymodel_url_idx', MyModel.url)  if __name__ == '__main__':     mymodel_url_index.create(bind=engine) 

Now where engine comes from will be up to your sqlalchemy configuration, but this code should convey the gist of what needs to happen.

like image 129
brthornbury Avatar answered Oct 12 '22 03:10

brthornbury