【发布时间】:2017-08-19 12:06:52
【问题描述】:
我有一个用于更新数据的 CSV 文件。更新不超过 15.000 条记录需要很长时间(大约 10 分钟)。 这是我使用的代码:
task csv_updater_so: :environment do
require 'csv'
counter = 0
time = Benchmark.realtime do
save_folder = Rails.root.join('path_to_file')
CSV.foreach(save_folder, encoding:'iso-8859-1:utf-8', col_sep: ';', :quote_char => "\x00", headers: true) do |row|
#If the item is in the db I update its values
if item = Item.find_by_internal_code(row[4])
item.update(:price => row[9], :stock_b => row[10])
end
counter += 1
print "updated items => #{counter}" + "\r"
end
end
end
我觉得很奇怪,从一个 xml 文件更新同一个模型只需要几秒钟。我做错了吗?
我也试过
task csv_updater_so: :environment do
require 'csv'
counter = 0
time = Benchmark.realtime do
save_folder = Rails.root.join('path_to_file')
updateable_items = CSV.foreach(save_folder, encoding:'iso-8859-1:utf-8', col_sep: ';', :quote_char => "\x00", headers: true).map do |row|
if item = Item.find_by_internal_code(row[4])
item.update(:price => row[9], :stock_b => row[10])
end
counter += 1
print "updated items => #{counter}" + "\r"
end
Item.import(updateable_items)
end
end
【问题讨论】:
-
您使用的是哪个版本的 Ruby 和 Rails?旧的 CSV 库确实非常慢。 (我问是因为
Item.find_by_internal_code是一种老式的查找器方法。) -
Ruby 2.3.3 和Rails 4.2.6 比较耗时的部分似乎是更新方式,但即使我使用“touch”也没有任何改善。
-
那么如果你删除更新行,脚本会在几秒钟内再次运行?
-
自您上次测量 XML 变体以来,您的数据库是否已显着增长?也许缺少索引?
-
没错,如果我删除更新行大约需要 10 秒
标签: ruby-on-rails ruby csv activerecord