Database Reference
In-Depth Information
Indexes significantly reduce the amount of work required to fetch documents.
Without the proper indexes, the only way to satisfy a query is to scan all docu-
ments linearly until the query conditions are met. This frequently means scan-
ning entire collections.
1
Only one single-key index will be used to resolve a query. 1 For queries contain-
ing multiple keys (say, ingredient and recipe name), a compound index con-
taining those keys will best resolve the query.
2
An index on ingredients can and should be eliminated if you have a second
index on ingredient-cuisine . More generally, if you have a compound index
on a-b , then a second index on a alone will be redundant. 2
3
The order of keys in a compound index matters.
4
Bear in mind that this cookbook analogy can be taken only so far. It's a model for
understanding indexes, but it doesn't fully correspond to the way MongoDB's indexes
work. In the next section, we'll elaborate on the rules of thumb just presented, and
we'll explore indexing in MongoDB in detail.
7.1.2
Core indexing concepts
The preceding thought experiment hinted at a number of core indexing concepts.
Here and throughout the rest of the chapter, we'll unpack those ideas.
S INGLE - KEY INDEXES
With a single-key index, each entry in the index corresponds to a single value from
each of the documents indexed. The default index on _id is a good example of a
single-key index. Because this field is indexed, each document's _id also lives in an
index for fast retrieval by that field.
C OMPOUND - KEY INDEXES
For the moment, MongoDB uses one index per query. 3 But you often need to query
on more than one attribute, and you want such a query to be as efficient as possible.
For example, imagine that you've built two indexes on the products collection from
this topic's e-commerce example: one index on manufacturer and another on price .
In this case, you've created two entirely distinct data structures that, when traversed,
are ordered like the lists you see in figure 7.2.
Now, imagine your query looks like this:
db.products.find({'details.manufacturer': 'Acme',
'pricing.sale': {$lt: 7500}})
This query says to find all Acme products costing less than $75.00. If you issue this
query with single-key indexes on manufacturer and price, only one of these will be
1
The one exception is queries using the $or operator. But as a general rule, this isn't possible, or even desir-
able, in MongoDB.
2
There are exceptions. If b is a multikey index, it may make sense to have indexes on both a-b and a .
3
There are rare exceptions to this rule. For instance, queries with $or may use a different index for each clause
of the $or query. But each individual clause by itself still uses just one index.
Search WWH ::




Custom Search