【问题标题】:Querying a composite key in SQLAlchemy-ORM在 SQLAlchemy-ORM 中查询复合键
【发布时间】:2015-03-31 19:17:41
【问题描述】:

背景

我在 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()

【问题讨论】:

  • BTW 背景研究:我尝试在 SO this waythis way 和 Google 搜索 this 上查找此内容,但未能找到合适的答案。

标签: python sqlalchemy flask-sqlalchemy composite-key


【解决方案1】:

是的,应该使用索引。 SQLAlchemy 没有使用索引,它只定义了索引。将它用于给定查询取决于数据库。

您可以使用EXPLAIN 来证明索引正在被使用。例如,PostgreSQL 显示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))

【讨论】:

    【解决方案2】:

    假设您的模型类名为Shirt,其中 (size, color) 是复合主键:

    您可以通过以下方式查询:

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

    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))
    

    【讨论】:

    • primary keys 可以,但是index 呢(就像 OP 问题中的那个)?
    猜你喜欢
    • 2021-09-21
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    相关资源
    最近更新 更多