mercredi 18 mars 2015

Improving query performance of with rails and mongo

Assuming that I have two models:



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


So, I have a controller method that calls Radar.retrieve_radars_and_stores, getting the result and returning as json.


The code works perfectly, however, having more than 20.000 records, it spends about 1 minute to process the method. Commenting out the stores: r.serializable_stores line, the method spends only few seconds.


My question is, how can I improve this query, reducing the time elapsed?


Thanks!


Aucun commentaire:

Enregistrer un commentaire