【问题标题】:find_each with order and limit带有订单和限制的 find_each
【发布时间】:2013-07-08 04:56:33
【问题描述】:

我需要限制和订购记录批次,并且正在使用 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

顺便说一句,我在 postgres 中有数据,我将获取一个子集并将其移动到 neo4j,因此我使用 neo4j 进行标记,以防你们中的任何 Neo4j 人知道如何执行此操作。谢谢。

【问题讨论】:

    标签: ruby-on-rails neo4j rails-postgresql


    【解决方案1】:

    不确定这是否是您要查找的内容,但您可以执行以下操作:

    weight = Thing.order(:weight).select(:weight).last(10_000_000).first.weight
    
    Thing.where("weight > ?", weight).find_each do |t|
     ...your code...
    end
    

    【讨论】:

      猜你喜欢
      • 2014-08-26
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 2022-10-31
      • 2015-08-10
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      相关资源
      最近更新 更多