gem*_*art 4 ruby csv activerecord ruby-on-rails activerecord-import
我正在尝试读取 5MM 行文件,但现在它超出了我在 heroku 上分配的内存使用量。我的方法有点快~200次插入/秒..我相信它在导入时崩溃了..所以我的计划是批量导入1,000或10,000个。我的问题是我如何知道我在文件的末尾,ruby 有一个.eof
方法,但它是一个File
方法,我不知道如何在我的循环中调用它
def self.import_parts_db(file)
time = Benchmark.measure do
Part.transaction do
parts_db = []
CSV.parse(File.read(file), headers: true) do |row|
row_hash = row.to_hash
part = Part.new(
part_num: row_hash["part_num"],
description: row_hash["description"],
manufacturer: row_hash["manufacturer"],
model: row_hash["model"],
cage_code: row_hash["cage_code"],
nsn: row_hash["nsn"]
)
parts_db << part
end
Part.import parts_db
end
end
puts time
end
Run Code Online (Sandbox Code Playgroud)
一旦使用File.read(file)
大文件,您的脚本就会使用大量内存(可能太多)。您将整个文件读入 1 个巨大的字符串,即使是CSV
逐行读取。
当您使用具有数千行的文件时,它可能会正常工作。不过,您应该使用CSV.foreach。改变
CSV.parse(File.read(file), headers: true) do |row|
Run Code Online (Sandbox Code Playgroud)
到
CSV.foreach(file, headers: true) do |row|
Run Code Online (Sandbox Code Playgroud)
在此示例中,内存使用量从 1GB 变为 0.5MB。
parts_db
变成一个巨大的零件数组,它不断增长,直到 CSV 文件的末尾。您需要删除事务(导入速度会很慢,但不需要比 1 行更多的内存)或批量处理 CSV。
这是一种可行的方法。我们CSV.parse
再次使用,但仅批量使用 2000 行:
def self.import_parts_db(filename)
time = Benchmark.measure do
File.open(filename) do |file|
headers = file.first
file.lazy.each_slice(2000) do |lines|
Part.transaction do
rows = CSV.parse(lines.join, write_headers: true, headers: headers)
parts_db = rows.map do |_row|
Part.new(
part_num: row_hash['part_num'],
description: row_hash['description'],
manufacturer: row_hash['manufacturer'],
model: row_hash['model'],
cage_code: row_hash['cage_code'],
nsn: row_hash['nsn']
)
end
Part.import parts_db
end
end
end
puts time
end
end
Run Code Online (Sandbox Code Playgroud)
前面的答案不应该使用太多内存,但导入所有内容仍然可能需要很长时间,对于远程服务器来说可能太多了。
使用枚举器的优点是可以轻松跳过批次并仅获取您想要的批次。
假设您的导入时间太长,并且在 424000 次成功导入后由于某种原因停止。
你可以替换:
file.lazy.each_slice(2000) do |lines|
Run Code Online (Sandbox Code Playgroud)
经过
file.lazy.drop(424_000).take(300_000).each_slice(2000) do |lines|
Run Code Online (Sandbox Code Playgroud)
跳过前 424000 行 CSV,并解析接下来的 300000 行。
对于下一次导入,请使用:
file.lazy.drop(424_000+300_000).take(300_000).each_slice(2000) do |lines|
Run Code Online (Sandbox Code Playgroud)
进而 :
file.lazy.drop(424_000+2*300_000).take(300_000).each_slice(2000) do |lines|
Run Code Online (Sandbox Code Playgroud)
...
归档时间: |
|
查看次数: |
3789 次 |
最近记录: |