Rails: Faster way to perform updates on many records

后端 未结 3 2056
执笔经年
执笔经年 2021-02-09 15:54

In our Rails 3.2.13 app (Ruby 2.0.0 + Postgres on Heroku), we are often retreiving a large amount of Order data from an API, and then we need to update or create each order in o

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-09 16:40

    Try wrapping your entire code into a single database transaction. Since you're on Heroku it'll be a Postgres bottom-end. With that many update statements, you can probably benefit greatly by transacting them all at once, so your code executes quicker and basically just leaves a "queue" of 6500 statements to run on Postgres side as the server is able to dequeue them. Depending on the bottom end, you might have to transact into smaller chunks - but even transacting 100 at a time (and then close and re-open the transaction) would greatly improve throughput into Pg.

    http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html http://www.postgresql.org/docs/9.2/static/sql-set-transaction.html

    So before line 2 you'd add something like:

    def add_details(shop, shopify_orders)
      Order.transaction do
        shopify_orders.each do |shopify_order|
    

    And then at the very end of your method add another end:

          if !payment_details.blank?
            PaymentDetail.add_details(order, payment_details)
          end
        end //shopify_orders.each..
      end //Order.transaction..
    end //method
    

提交回复
热议问题