提高rails和mongo的查询性能

时间:2015-03-18 19:56:30

标签: ruby-on-rails-3 performance mongodb mongomapper

假设我有两个模型:

class Radar
  include MongoMapper::Document
  plugin MongoMapper::Plugins::IdentityMap

  key :name,    String, :required => true
  key :slug,    String, :required => true
  many :stores, index: true

  def self.retrieve_radars_and_stores
    radars = Radar.all
    radars.map { |r|
      {
        name:   r.name,
        ip:     r.ip,
        stores: r.serializable_stores
      }
    }
  end

  def serializable_stores
    stores.map { |store|
      {
        name:     store.try(:name),
        location: store.try(:location)
      }
    }
  end
end

class Store
  include MongoMapper::Document

  key :name, String,     :required => true
  key :location, String, :required => true

  ensure_index :name
  ensure_index :location
end

所以,我有一个调用Radar.retrieve_radars_and_stores的控制器方法,得到结果并返回为json。

代码完美无缺,但是,有超过20.000条记录,它花费大约1分钟来处理该方法。在评论stores: r.serializable_stores行时,该方法仅花费几秒钟。

我的问题是,如何改进此查询,减少已用时间?

谢谢!

0 个答案:

没有答案