python - 在 SQLAlchemy-ORM 中查询组合键

标签 python sqlalchemy flask-sqlalchemy composite-key

背景

我在 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 复合索引搜索 smallred 衬衫。

如何编写此查询?

使用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/

相关文章:

transactions - 如何在使用数据库 session 的同时使用sql alchemy中的事务?

python - Heroku 计划任务每​​ 10 分钟运行一次,每小时计划一次

python - 如何可靠地找到图像上的复选框(使用 cv2.findContours 或其他技术)?

python - 如何使Python中的多个if语句运行得更快

flask - Sqlalchemy - 加入后分组

python - Flask-Sqlalchemy:具有 3 个主键同时也是外键的表

Python flask : How to correctly query a select field?

python - 从列唯一值创建列

python - 在 SQLAlchemy 中使用 PostgresQL INTERVAL,其中持续时间动态存储在数据库中并且不是参数

python - 无法使用 SQLAlchemy 和 pymssql 连接到 Azure SQL