背景
我在 SQLAlchemy 对象上定义了一个复合索引,例如:
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)
<小时/>
问题
我现在想利用 color_size
复合索引搜索 small
和 red
衬衫。
如何编写此查询?
使用and_()
会自动利用索引吗?
例如:
results = Shirt.query.filter( and_(Shirt.size=='small', Shirt.color=='red') ).all()
最佳答案
是的,应该使用索引。但 SQLAlchemy 不使用索引,它仅定义索引。由数据库决定将其用于给定的查询。
您可以使用EXPLAIN
证明该索引正在被使用。例如,PostgreSQL 显示索引扫描
。
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))
关于python - 在 SQLAlchemy-ORM 中查询组合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29376721/