加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 提高查询性能

发布时间:2020-12-20 13:36:15 所属栏目:Python 来源:网络整理
导读:我需要从PostgreSQL数据库中读取并加入很多行(~500k)并将它们写入 MySQL数据库. 我天真的做法看起来像这样 entrys = Entry.query.yield_per(500) for entry in entrys: for location in entry.locations: mysql_location = MySQLLocation(entry.url) mysql_l
我需要从PostgreSQL数据库中读取并加入很多行(~500k)并将它们写入 MySQL数据库.

我天真的做法看起来像这样

entrys = Entry.query.yield_per(500)

    for entry in entrys:
        for location in entry.locations:
            mysql_location = MySQLLocation(entry.url)
            mysql_location.id = location.id
            mysql_location.entry_id = entry.id

            [...]

            mysql_location.city = location.city.name
            mysql_location.county = location.county.name
            mysql_location.state = location.state.name
            mysql_location.country = location.country.name

            db.session.add(mysql_location)

    db.session.commit()

每个条目有大约1到100个地点.

此脚本现在正在运行大约20个小时,已经消耗了> 4GB的内存,因为所有内容都保存在内存中,直到会话提交.

我早先尝试提交,我遇到了像this这样的问题.

如何提高查询性能?它需要更快,因为在接下来的几个月里,行数将增长到大约2500k.

解决方法

你天真的方法是有缺陷的,因为你已经知道 – 吃内存的东西是悬挂在内存中等待刷新到mysql的模型对象.

最简单的方法是根本不使用ORM进行转换操作.直接使用SQLAlchemy表对象,因为它们也更快.

此外,您可以做的是创建2个会话,并将2个引擎绑定到单独的会话中!然后,您可以为每个批处理提交mysql会话.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读