减少从大型 SQLAlchemy 数据库中检索行的时间

Reduce row retrieval time from big SQLAlchemy database

在我的金字塔应用程序中我有 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)

我的artisttable有85632行,followers辅助table有420749行。

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

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

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

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

解决方案:

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