2013-07-08 77 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