使用cursor.copy_from() 的psycopg2 COPY 在大输入时冻结
考虑以下 Python 代码,使用 psycopg2 cursor
对象(为了清楚起见,更改或省略了一些列名称):
filename='data.csv'
file_columns=('id', 'node_id', 'segment_id', 'elevated',
'approximation', 'the_geom', 'azimuth')
self._cur.copy_from(file=open(filename),
table=self.new_table_name, columns=file_columns)
- 数据库位于快速 LAN 上的远程计算机上。
- 使用 bash 中的
\COPY
工作速度非常快,即使对于大型(~1,000,000 行)文件也是如此。
该代码对于 5,000 行来说速度非常快,但是当 data.csv
增长超过 10,000 行时,程序会完全冻结。
有什么想法\解决方案吗?
亚当
Consider the following code in Python, using psycopg2 cursor
object (Some column names were changed or omitted for clarity):
filename='data.csv'
file_columns=('id', 'node_id', 'segment_id', 'elevated',
'approximation', 'the_geom', 'azimuth')
self._cur.copy_from(file=open(filename),
table=self.new_table_name, columns=file_columns)
- The database is located on a remote machine on a fast LAN.
- Using
\COPY
from bash works very fast, even for large (~1,000,000 lines) files.
This code is ultra-fast for 5,000 lines, but when data.csv
grows beyond 10,000 lines, the program freezes completely.
Any thoughts \ solutions?
Adam
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这只是一种解决方法,但您可以将某些内容通过管道传输到 psql 中。有时,当我懒得摆脱 psycopg2 时,我会使用这个食谱
就你的锁定而言,你是否使用多线程或类似的东西?
你的 postgres 是否记录了诸如关闭连接或死锁之类的信息?锁定后您能看到磁盘活动吗?
This is just a workaround, but you can just pipe something into psql. I use this recipe sometimes when I am too lazy to bust out psycopg2
As far as your locking up is concerned, are you using multiple threads or anything like that?
Is your postgres logging anything such as a closed connection or a deadlock? Can you see disk activity after it locks up?
这是内存限制,导致“copy_from”崩溃,因为 open(filename) 一次性返回所有文件。这是 psycopg2 的问题,而不是 Postgresql 的问题,所以 Mike 的解决方案是最好的。
如果您想在常规提交中使用“copy_from”并同时管理重复键,有一个解决方案:
https://stackoverflow.com/a/11059350/1431079
That's memory limitation which makes "copy_from" crashing as open(filename) returns all the file in one shot. It's a psycopg2's problem, not Postgresql one, so Mike's solution is the best one.
There is a solution if you want to use "copy_from" with regular commits and manage duplicate keys at the same time:
https://stackoverflow.com/a/11059350/1431079