Partial indexes

A partial index on a collection is an index that only applies to the documents that satisfy the partialFilterExpression query.

We'll use our familiar books collection, as follows:

> db.books.createIndex(
{ price: 1, name: 1 },
{ partialFilterExpression: { price: { $gt: 30 } } }
)

Using this, we can have an index for just the books that have a price greater than 30. The advantage of partial indexes is that they are more lightweight in creation and maintenance, and use less storage.

The partialFilterExpression filter supports the following operators:

  • Equality expressions (that is, field: value, or using the $eq operator)
  • The $exists: true expression
  • The $gt, $gte, $lt, and $lte expressions
  • $type expressions
  • The $and operator, at the top level only

Partial indexes will only be used if the query can be satisfied as a whole by the partial index.

If our query matches or is more restrictive than the partialFilterExpression filter, then the partial index will be used. If the results may not be contained in the partial index, then the index will be totally ignored.

partialFilterExpression does not need to be a part of the sparse index fields. The following index is a valid sparse index:


> db.books.createIndex({ name: 1 },{ partialFilterExpression: { price: { $gt: 30 } } })

To use this partial index, however, we need to query for both name and price equal to or greater than 30.

Prefer partial indexes to sparse indexes. Sparse indexes offer a subset of the functionality offered by partial indexes. Partial indexes were introduced in MongoDB 3.2, so if you have sparse indexes from earlier versions, it may be a good idea to upgrade them. The _id field cannot be a part of a partial index. A shard key index cannot be a partial index. partialFilterExpression cannot be combined with the sparse option.
..................Content has been hidden....................

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