最有效的方法避免将重复行注入Postgres DB
这更多的是一个概念性问题。我正在使用 python 和 psycopg2 库构建一个关系数据库,并且有一个包含超过 4400 万行(并且还在不断增长)的表,我想尝试将 csv 文件中经过清理的行注入到其中不注入重复行的表;每行都有一个来自其原始数据库表的自动递增的唯一 ID。
我注入数据的当前方式是使用 COPY table(列...) FROM '/path/to/file'
命令;这就像一个魅力。在我们清理 csv 文件中的所有行以将行中的数据类型与表中相应列的数据类型相匹配之后,就会发生这种情况。
我有一些想法,并且我已经尝试过,但想在实施之前看看最有效的选择是什么。
我尝试的那个最终给服务器的CPU和内存带来了巨大的负担;我们决定不再继续。我最终创建了一个脚本,该脚本对数据库进行查询,搜索表中的唯一 ID(超过 4400 万行)。
我的其他理想解决方案:
允许注入重复项,然后创建一个脚本来清理表中的任何重复行。
使用 csv 中的数据创建临时表。将临时表与现有表进行比较,从临时表中删除所有重复值,然后将临时表注入到现有表中。
通过此问题可以简化第 2 步< /a>.我们不比较两个表,而是使用
INSERT INTO
命令和ON CONFLICT
选项。这可能更多的是想象力的延伸,并且可能对我们的情况来说非常独特。但是,由于我们知道唯一 id 字段将自动递增,因此我们可以将全局变量设置为等于表中最大的唯一 id 值,然后在清理数据之前我们进行查询以检查唯一 id 值是否小于比全局变量数据,如果这是(不再是一个选项)True
,我们会丢弃该行以防止注入。
This is more of a conceptual question. I'm building a relational db, using python and the psycopg2
library, and have a table that has over 44 million rows (and growing) that I want to try and inject sanitized rows from a csv file into the table without injecting duplicate rows; each row has an auto incrementing unique id from it's origin db table.
The current way I'm injecting the data is using the COPY table(columns...) FROM '/path/to/file'
command; which is working like a charm. This occurs after we've sanitized all rows in the the csv file to match the datatypes in the rows to the appropriate column's datatypes in the table.
There are a few ideas that I have in mind, and one I've tried, but want to see what the most efficient option is before implementation.
The one I tried ended up being a tremendous burden on the server's cpu and memory; which we have decided not to proceed on. I ended up creating a script that makes a query to the db that searches for the unique id in the table (over 44 million rows).
My other idealistic solutions:
Allow injection of duplicates then create a script to clean up any duplicate rows in the table.
Create a temporary table with the data from the csv. Compare the temp table with the existing table, removing any duplicate values from the temp table, then injecting the temp table into the existing table.
Step 2 might be simplified with this issue. Instead of comparing the two tables we just use the
INSERT INTO
command along with theON CONFLICT
option.This one might be more of a stretch of the imagination, and probably pretty unique to our situation. But, since we know that the unique id field will be auto incrementing, we can set a global variable to equal the largest unique id value in the table, then before sanitizing the data we make a query to check if the unique id value is less than the global variable data, and if that is(No longer an option)True
, we throw out the row from being injected.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论