Drop and read index using SQLAlchemy

Question:

I want to do a bulk insertion in SQL alchemy and would prefer to remove an index prior to making the insertion, reading it when the insertion is complete.

I see adding and removing indexes is supported by Alembic for migrations, but is this possible with SQLAlchemy? If so, how?

Asked By: Eric Baldwin

||

Answers:

The best method is to just execute sql. In this casesession.execute("DROP INDEX ...")

Answered By: Eric Baldwin

So, I’ve been struggling with this. It seems that SQLAlchemy (v1.4 with the v2.0 compatibility routines running) drops the physical index but, at least in my case, doesn’t update its metadata to reflect that. The following code seems to get over that issue…

ndx_to_drop.drop()
# SQLAlchemy drops the index but doesn't update our index metadata, requiring the following
loc_indexes = tbl.indexes.copy()
loc_indexes = {loc_ndx for loc_ndx in loc_indexes if loc_ndx.name !=ndx_to_drop.name}
tbl.indexes = loc_indexes
Answered By: Ben
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.