Querying a composite key in SQLAlchemy-ORM -
background
i have composite index defined on sqlalchemy object, say:
class shirt(base): __tablename__ = 'shirt' id = column(integer, primary_key=true) size = column(string(32)) # e.g. small, medium large color = column(string(32)) # e.g. blue, red, white index('color_size', shirt.size, shirt.color)
question
i'd search small
, red
shirts, taking advantage of color_size
composite index.
how write query?
would use of and_()
automatically take advantage of index?
example:
results = shirt.query.filter( and_(shirt.size=='small', shirt.color=='red') ).all()
yes, index should used. sqlalchemy isn't using index though, defines index. it's database use given query.
you can use explain
prove index being used. example, postgresql shows index scan
.
example => explain select id shirt color = 'red' , size = 'small'; query plan ---------------------------------------------------------------------------------- index scan using ix_shirt_size_color on shirt (cost=0.15..8.17 rows=1 width=4) index cond: (((size)::text = 'small'::text) , ((color)::text = 'red'::text))
Comments
Post a Comment