ということでメモ程度ですが書いときます。

Railsには find_each というメソッドが用意されています。通常の each メソッドを使用すると、全データをまとめてメモリに展開してから処理を開始します。そのため、十分にメモリに載るデータ量であれば何も問題ないですが、数百万、数千万というデータ量になってくるとメモリに載りきらずに溢れてしまって大変なことになります。

find: 全データをメモリに展開してから処理
find_each: 少しずつデータをメモリに展開しつつ処理

そういうときには find_each メソッドを使いましょう。これは少しずつデータをメモリに展開して処理を行います(デフォルトでは1,000件ずつ)。全部まとめてではなくちょっとずつメモリに展開してくれるため、大量のデータを処理するような場合でも問題なく処理できます。

ちなみによく似たメソッドに find_in_batches がありますが、これは例えばデフォルトで1,000件ずつデータを取ってきたときに、それらのデータが1件ずつ処理されるか配列でまとめて処理されるかという違いです。 find と同じ感覚で使うなら find_each の方が便利ですかね。

find_each: 取ってきたデータは1件ずつ処理 (yield) される
find_in_batches: 取ってきたデータは配列でまとめて処理 (yield) される

# find_in_batches ( yield records )
def find_in_batches(options = {})
  relation = self

  unless arel.orders.blank? && arel.taken.blank?
    ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
  end

  if (finder_options = options.except(:start, :batch_size)).present?
    raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order].present?
    raise "You can't specify a limit, it's forced to be the batch_size"  if options[:limit].present?

    relation = apply_finder_options(finder_options)
  end

  start = options.delete(:start).to_i
  batch_size = options.delete(:batch_size) || 1000

  relation = relation.reorder(batch_order).limit(batch_size)
  records = relation.where(table[primary_key].gteq(start)).all

  while records.any?
    records_size = records.size
    primary_key_offset = records.last.id

    yield records

    break if records_size < batch_size

    if primary_key_offset
      records = relation.where(table[primary_key].gt(primary_key_offset)).to_a
    else
      raise "Primary key not included in the custom select clause"
    end
  end
end

#find_each ( yield record )
def find_each(options = {})
  find_in_batches(options) do |records|
    records.each { |record| yield record }
  end
end
このエントリーをはてなブックマークに追加