Index intersection

Index intersection refers to the concept of using more than one index to fulfill a query. This was added fairly recently, and is not perfect yet; however we can exploit it to consolidate our indexes.

We can verify whether an index intersection happened in a query by using explain() on the query and witnessing an AND_SORTED or AND_HASH stage in the executed query plan.

Index intersection can happen when we use OR ($or) queries, by using a different index for each OR clause. Index intersection can happen when we use AND queries, and we have either complete indexes for each AND clause or index prefixes for some (or all) of the clauses.

For example, consider a query on our books collection, as follows:

> db.books.find({ "isbn":"101", "price": { $gt: 20 }})

Here, with two indexes (one on isbn and the other on price), MongoDB can use each index to get the related results, and then intersect on the index results to get the result set.

With compound indexes, as you learned previously in this chapter, we can use index prefixing to support queries that contain the first 1…n-1 fields of an field compound index.

What we cannot support with compound indexes are queries that are looking for fields in the compound index, missing one or more of the previously defined fields.

The order matters in compound indexes.

To satisfy these queries, we can create indexes on the individual fields, which will then use index intersection and fulfill our needs. The down side to this approach is that as the number of fields (n) increases, the number of indexes that we have to create grows exponentially, thus increasing our need for storage and memory.

Index intersection will not work with sort(). We can't use one index for querying and a different index for applying sort() to our results.

However, if we have an index that can fulfill a part for the whole of our query and the sort() field, then this index will be used.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset