1

Background

I have a composite index defined on a 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 now like to do a search for small and red shirts, taking advantage of the color_size composite index.

How do I write this query?

Would the use of and_() automatically take advantage of the index?
For example:

results = Shirt.query.filter( and_(Shirt.size=='small', Shirt.color=='red') ).all()
1
  • BTW background research: I tried looking this up on SO this way and this way and Googled this but have not been able to find a suitable answer. Commented Mar 31, 2015 at 19:20

2 Answers 2

2

Yes, the index should be used. SQLAlchemy isn't using the index though, it only defines the index. It's up to the database to use it for a given query.

You can use EXPLAIN to prove that the index is being used. For example, PostgreSQL shows an Index Scan.

example => explain select id from shirt where color = 'red' and 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) AND ((color)::text = 'red'::text))
Sign up to request clarification or add additional context in comments.

Comments

-1

Assuming your model class is called Shirt with (size, color) is the composite primary key:

You can query either with:

import sqlalchemy
...
Example.query.get((size, color))

or

import sqlalchemy
from sqlalchemy.orm import sessionmaker
...
engine = sqlalchemy.create_engine('postgresql://user:pass@localhost/db_name')
session = sessionmaker(bind=engine)()
session.query(Example).get((size, color))

1 Comment

Ok for primary keys but what about index (like the one in the OP question)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.