我正在对300,000条记录运行简单的rails active查询命令。
为什么heroku控制台自动退出?
def is_number? string
true if Float(string) rescue false
end
documents = []
DocumentText.all.each do |t|
if is_number?(t.src)
documents << t
end
end
尝试避免在repl上加载大量数据
DocumentText.select('src').each do |t|
if is_number?(t.src)
documents << t
end
end;nil
最好是分批执行,因此您不会一次将所有记录加载到内存中
https://api.rubyonrails.org/classes/ActiveRecord/Batches.html#method-i-find_each
DocumentText.find_each do |t|
next unless !!Float(t.src) rescue false
documents << t
end; nil
nil
最后不会在控制台中显示结果,您也可以使用数字0
可能更容易在数据库端进行过滤,例如
DocumentText
.select('src::float as src')
.where("src ~ '^([0-9]+[.]?[0-9]*|[.][0-9]+)$'")
.map(&:src);nil
这里我们将src强制转换为一个浮点数,其中src符合给定的模式。强制转换对您可能并不重要,但是where子句将在数据库中过滤您的结果,而不是全部加载然后过滤它们。