2013-07-08 78 views
2

我需要限制和訂購批次的記錄,並使用find_each。我見過很多人要求這個,也沒有很好的解決方案。如果我錯過了,請發佈鏈接!find_each與訂單和限制

我有30M記錄,想要處理重量欄中最高值的10M。

我試過使用這種方法有人寫道:find_each_with_order,但不能得到它的工作。

來自該網站的代碼並未將訂單作爲選項。看起來很奇怪,因爲名字是find_each_with_order。我說,如下所示:

class ActiveRecord::Base 
# normal find_each does not use given order but uses id asc 
def self.find_each_with_order(options={}) 
    raise "offset is not yet supported" if options[:offset] 
    page = 1 
    limit = options[:limit] || 1000 
    order = options[:order] || 'id asc'  
    loop do 
    offset = (page-1) * limit 
    batch = find(:all, options.merge(:limit=>limit, :offset=>offset, :order=>order)) 
    page += 1 
    batch.each{|x| yield x } 
    break if batch.size < limit 
    end 
end 

我試圖按如下方式使用它:

class GetStuff 
    def self.grab_em 
    file = File.open("1000 things.txt", "w") 
    rels = Thing.find_each_with_order({:limit=>100, :order=>"weight desc"}) 
    binding.pry 
    things.each do |t| 
     binding.pry 
     file.write("#{t.name} #{t.id} #{t.weight}\n") 
     if t.id % 20 == 0 
     puts t.id.to_s 
     end 
    end 
    file.close 
    end 
end 

BTW我在Postgres的數據和我會抓住一個子集,並將其移到的Neo4j ,所以我用neo4j標記,以防neo4j的任何人知道如何做到這一點。謝謝。

回答

0

不完全相信,如果這是你在尋找什麼,但你可以做這樣的事情:

weight = Thing.order(:weight).select(:weight).last(10_000_000).first.weight 

Thing.where("weight > ?", weight).find_each do |t| 
...your code... 
end