【发布时间】:2022-01-10 12:37:42
【问题描述】:
(已回答)我对此的回答在下方,希望对您有所帮助。
我对 SQLAlchemy 和 Python 很陌生,我正在寻找一些建议。我正在考虑将数据从一个 Postgres DB 移动到另一个 Postgres DB。我要移动 2000 万多条记录,我希望这项工作每天都运行。我想知道:
- 我应该使用 SQLAlchemy 核心还是 ORM? (我主要使用核心 到目前为止)
- 我目前正在使用 SQLAlchemy 版本 '1.3.23'(我应该移动到 1.4/2.x)?
- 如何优化插入以更快地运行? (听说可能需要启用一些标志?)
很遗憾,我无法使用 pyscopg2 复制功能,因为我没有超级用户访问数据库的权限。
我正在尝试关注别人的堆栈溢出示例:the example i am following
q = select([table_1])
proxy = conn_p.execution_options(stream_results=True).execute(q)
while 'batch not empty': # equivalent of 'while True', but clearer
batch = proxy.fetchmany(100000) # 100,000 rows at a time
if not batch:
break
for row in batch:
???
proxy.close()
我卡住的部分是在 for 循环中。如何将数据写入下一个数据库? 我应该使用什么功能?
这是最好的方法还是我犯了严重的错误?
我当前使用 1.4 版的代码迭代:
conn_p = create_engine(--db connection string--, echo=True)
conn_sl = create_engine(--db connection string--, echo=False)
q = select([table_1])
proxy = conn_p.execution_options(stream_results=True).execute(q)
while 'batch not empty':
batch = proxy.fetchmany(10000)
list1 = []
if not batch:
break
for row in batch:
d = dict(row.items())
list1.append(d)
insert_stmt = table_2.insert().values(list1)
conn_sl.execute(insert_stmt)
proxy.close()
仍然很慢,移动 10k 条记录大约需要 15 秒。 有什么建议吗?
【问题讨论】:
-
@GordThompson 我已经像
conn_sl = create_engine(--db connection string--, echo=False, executemany_mode='values')那样将标志添加到我的连接中,但我没有看到任何性能增强。我错过了什么吗?我只做 INSERT 没有更新或类似的事情。我只是想移动数据。 -
values_only是 SQLAlchemy 1.4 的默认值,听起来像你想要的 -
我更新到 1.4 并运行了这段代码(添加到我上面的问题中)。我以相同的速度移动 10k 记录需要 15 秒,而 100k 需要 2 分半钟。
-
您是通过 WAN 还是云连接将数据推送到目标数据库?
标签: python postgresql sqlalchemy