循环大小超过一百万的数组然后插入数据库的最有效方法

时间:2016-11-10 01:41:22

标签: ruby-on-rails arrays postgresql optimization bulkinsert

我有array of records,最有可能有length of million or more than that。我需要将其从每条记录循环到select few attributes,然后bulk insert them to a table

我得到的最简单的版本是这样的:

objs = []
workers.each do |w|
  temp = {}
  temp[:person_id] = w.id
  temp[:working_hours] = time
  objs << temp
end
WorkHours.create(objs)

所以workers是一个数组,它总是包含超过一百万的记录。现在,我只需从每个attributes中选择一些record,然后将它们批量插入WorkHours表。

我需要知道可以在哪些方面改进此代码以及如何在此处完成批量插入。如需参考,请使用Postgres数据库和rails 4.2

了解这个gem但不确定。

0 个答案:

没有答案