I'm new to MongoDB and trying to make sure I set up the proper indexes. I've seen similar questions about composite indexes here but none that exactly cover the situation I'm in.
Note: I'm using Rails 3.2 and Mongoid.
I have a collection of Events that are always going to be sorted (and often searched on) date, but generally with another parameter as well. For example, I might want to find the Events that match a particular set of categories within a certain date range; or I might want to find the Events that match a particular person within a certain date range. The types of searches will be:
- Always by date (or at least sorting by date)
- Often by category
- Sometimes additionally by [person, venue, or keyword]
The first solution I came up with was multiple composite keys that all start with date and category, like so:
class Event
...
index ([
[:date, Mongo::DESCENDING],
[:category_id, Mongo::ASCENDING]
["people.person_id", Mongo::ASCENDING]
])
index ([
[:date, Mongo::DESCENDING],
[:category_id, Mongo::ASCENDING]
[:venue_id, Mongo::ASCENDING]
])
index ([
[:date, Mongo::DESCENDING],
[:category_id, Mongo::ASCENDING]
[:keywords, Mongo::ASCENDING]
])
But it seems a little funny to me to keep overlapping the "date + category_id" index, and also what about the cases when I'm not searching on category_id?
UPDATE: dcrosta asked what kind of queries would be running, and how frequently. Without knowing exactly, I can guess that it would look something like the following:
Very frequent:
- by date
- by date + category
- by date + keyword
- by date + category + keyword
Somewhat frequent:
- by date + person
- by date + venue
Less frequent:
- by date + category + venue
- by date + category + person