ruby-on-rails - 在 Ruby/Rails 中处理大型数据集导入

标签 ruby-on-rails ruby postgresql activerecord benchmarking

我目前正在使用 Ruby/Rails 进行一个项目,将发票导入数据库,但试图最大限度地提高流程的效率,目前确实太慢了。

对于具有 100.000 行的导入批处理,处理和保存数据库中的每条记录大约需要 2.5 3 小时。

//// ruby 代码

  class DeleteImportStrategy
def pre_process(merchant_prefix, channel_import)
  # channel needed to identify invoices so an import from another channel cannot collude if they had same merchant_prefix
  Jzbackend::Invoice.where(merchant_prefix: merchant_prefix, channel: channel_import.channel).delete_all
  # get rid of all previous import patches which becomes empty after delete_import_strategy
  Jzbackend::Import.where.not(id: channel_import.id).where(channel: channel_import.channel).destroy_all
end

def process_row(row, channel_import)
  debt_claim = Jzbackend::Invoice.new
  debt_claim.import = channel_import
  debt_claim.status = 'pending'
  debt_claim.channel = channel_import.channel
  debt_claim.merchant_prefix = row[0]
  debt_claim.debt_claim_number = row[1]
  debt_claim.amount = Monetize.parse(row[2])
  debt_claim.print_date = row[3]
  debt_claim.first_name = row.try(:[], 4)
  debt_claim.last_name = row.try(:[], 5)
  debt_claim.address = row.try(:[], 6)
  debt_claim.postal_code = row.try(:[], 7)
  debt_claim.city = row.try(:[], 8)
  debt_claim.save
end

结束

////

因此,对于以 CSV 格式传入的每个导入批处理,我摆脱了以前的批处理,开始导入新的批处理,方法是读取每一行并将其插入到新的“作为发票导入”记录中。但是,100.000 个条目需要 2.5-3 小时似乎有点矫枉过正。我如何才能优化这个过程,因为我确信这种方式绝对没有效率。

编辑: 所以我已经很久没有发布这个了,但要注意的是,我最终使用了 activerecord-import 库,从那时起它运行得很好。但是,请注意它的 :on_duplicate_key_update 功能仅在 PostgreSQL v9.5+ 中可用。

最佳答案

批量导入的第一条规则:批量,批量,批量。

您要分别保存每一行。这会产生巨大的开销。比如说,插入本身需要 1 毫秒,但到数据库的往返是 5 毫秒。总使用时间 - 6 毫秒。对于 6000 毫秒或 6 秒的 1000 条记录。

现在假设您使用批量插入,在同一语句中为多行发送数据。它看起来像这样:

INSERT INTO users (name, age)
VALUES ('Joe', 20), ('Moe', 22), ('Bob', 33'), ...

假设您在这个请求中发送了 1000 行的数据。请求本身需要 1000 毫秒(但实际上它也可能会快得多,解析查询、准备执行计划等的开销更少)。总耗时为 1000ms + 5ms。至少减少 6 倍! (在我的实际项目中,我观察到减少了 100 到 200 倍)。

关于ruby-on-rails - 在 Ruby/Rails 中处理大型数据集导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45730887/

相关文章:

ruby-on-rails - Ruby on Rails 帮助程序缓存评估值

ruby-on-rails - 登录后更新属性设计

ruby-on-rails - 从 postgres db 接收 IP 地址的所有匹配网络

ruby-on-rails - Rails 3 路由、Yaml 和转义 UTF-8

ruby - RSpec 3 中 pending 或 skip 的替代方案

用于检查应用程序中有多少行代码的 Ruby 脚本

java - 带有大表的 setMaxResults 使用太多内存

regex - 在 postgres 中一起使用 REPLACE 和 LIKE

c# - 使用Dataadapter更新时出现DBConcurrency异常

ruby-on-rails - Ruby:警告:您正在将 Rubygems 2.0.14 与 Spring 一起使用。至少升级到 Rubygems 2.1.0