减少来自大型SQLAlchemy数据库的行检索时间

时间:2017-08-13 14:57:36

标签: python database performance sqlalchemy 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行。

目前,如果我尝试像这样检索某些followed的{​​{1}}:

artist

查询大约需要30-40毫秒来检索行,我怎样才能改进模型以减少这段时间?

顺便说一下,我的db.query(Artist).first().folowed.all() 模型基于此tutorial

1 个答案:

答案 0 :(得分:0)

解决方案:

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