【发布时间】:2021-02-05 03:37:36
【问题描述】:
我有一个传入的 CSV,我试图将它与现有的 mongo 文档集合(Note 对象)进行比较,以确定添加、删除和更新。传入的 CSV 和 mongo 集合非常大,每个都有大约 50 万条记录。
例如。 csv_data
[{
id: 1, text: "zzz"
},
{
id: 2, text: "bbb"
},
{
id: 4, text: "ddd"
},
{
id: 5, text: "eee"
}]
Note 对象的 Mongo 集合:
[{
id: 1, text: "aaa"
},
{
id: 2, text: "bbb"
},
{
id: 3, text: "ccc"
},
{
id: 4, text: "ddd"
}]
结果我想得到
添加的数组
[{
id: 5, text: "eee"
}]
删除数组
[{
id: 3, text: "ccc"
}]
一组更新
[{
id: 1, text: "zzz"
}]
我尝试使用 select 语句来过滤每个特定差异,但在使用包含所有 500k 记录的真实数据集时它会失败/需要数小时。
additions = csv_data.select{|record| !Note.where(id: record[:id]).exists?}
deletions = Note.all.select{|note| !csv_data.any?{|row| row[:id] == note.id}}
updates = csv_data.select do |record|
note = Note.where(id: record[:id])
note.exists? && note.first.text != record[:text]
end
如何更好地优化它?
【问题讨论】:
-
阅读 N+1 个查询,这是一个反模式
标签: ruby-on-rails ruby mongodb