【问题标题】:Reduce row retrieval time from big SQLAlchemy database减少大型 SQLAlchemy 数据库的行检索时间
【发布时间】:2017-08-13 14:57:35
【问题描述】:

在我的 Pyramid 应用程序中,我有 models.py:

db = scoped_session(sessionmaker())
Base = declarative_base()

followers = Table('followers',
                  Base.metadata,
                  Column('follower_id', Integer, ForeignKey('artist.id')),
                  Column('followed_id', Integer, ForeignKey('artist.id')))

class Artist(Base):
    __tablename__ = 'artist'
    id = Column(Integer, primary_key=True)
    title = Column(Text)

    followed = relationship('Artist',
                                   secondary=followers,
                                   primaryjoin=(followers.c.follower_id == id),
                                   secondaryjoin=(followers.c.followed_id == id),
                                   backref=backref('followers', lazy='dynamic'),
                                   lazy='dynamic')

Index('my_index', Artist.id, unique=True, mysql_length=255)

我的artist 表有 85,632 行,followers 辅助表有 420,749 行。

目前,如果我尝试像这样检索一些artist 中的followed

db.query(Artist).first().folowed.all()

查询需要大约 30-40 毫秒来检索行,我该如何改进我的模型以减少这个时间?

顺便说一下,我的Artist 模型是基于这个tutorial

【问题讨论】:

  • 尝试使用 InnoDB,这样 ForeignKeys 由数据库处理,而不是由 SQLAlchemy。
  • 我将__table_args__ = {'mysql_engine': 'InnoDB'} 添加到我的class Artist 模型中。我必须升级我的数据库吗?
  • 尝试在followers.follower_id上添加索引。
  • 我添加了两个建议,每个查询的时间减少到 2 毫秒左右,谢谢!

标签: python database performance sqlalchemy pyramid


【解决方案1】:

解决方案:

  • 使用InnoDB,这样ForeignKeys 由数据库处理,而不是由SQLAlchemy。
  • 索引字段followers.follower_id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 2021-11-10
    • 1970-01-01
    • 2015-06-22
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多