Is it possible to specify what index a query should use in Mongoid?
MongoDB seems like it is using an inefficient query pattern when one index is a subset of another index.
class Model
  field :status, :type => Integer
  field :title, :type => String
  field :subtitle, :type => String
  field :rating, :type => Float
  index([
    [:status, Mongo::ASCENDING],
    [:title, Mongo::ASCENDING],
    [:subtitle, Mongo::ASCENDING],
    [:rating, Mongo::DESCENDING]
  ])
  index([
    [:status, Mongo::ASCENDING],
    [:title, Mongo::ASCENDING],
    [:rating, Mongo::DESCENDING]
  ])
end
Th开发者_开发问答e first index is being used both when querying on status, title and subtitle and sorting on rating and when querying on just status and title and sorting on rating even though using explain() along with hint() in the javascript console states that using the second index is 4 times faster.
How can I tell Mongoid to tell MongoDB to use the second index?
You can pass options such as hint to Mongo::Collection using Mongoid::Criterion::Optional.extras
An example:
criteria = Model.where(:status => true, :title => 'hello world').desc(:rating)
criteria.extras(:hint => {:status => 1, :title => 1, :rating => -1})
extras accepts anything that Mongo::Collection can handle
http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint
While the mongo query optimizer often performs very well, explicit "hints" can be used to force mongo to use a specified index, potentially improving performance in some situations.
db.collection.find({user:u, foo:d}).hint({user:1});
You need to work from http://www.rdoc.info/github/mongoid/mongoid/master/Mongoid/Cursor here as I do not know Ruby enough. It mentions hint.
 加载中,请稍侯......
      
精彩评论