I've read official docs of MongoDB but really can't understand the difference between sparse and partial indexes. I wanted to have an explanatory view with examples.
Partial indexes only index the documents in a collection that meet a specified filter expression. By indexing a subset of the documents in a collection, partial indexes have lower storage requirements and reduced performance costs for index creation and maintenance.
Dense Index: It has index entries for every search key value (and hence every record) in the database file. The dense index can be built on order as well as unordered fields of the database files. Sparse Index: It has index entries for only some of the search key values/records in the database file.
A partial index is an index built over a subset of a table; the subset is defined by a conditional expression (called the predicate of the partial index). The index contains entries only for those table rows that satisfy the predicate.
MongoDB provides two geospatial indexes known as 2d indexes and 2d sphere indexes using these indexes we can query geospatial data. Here, the 2d indexes support queries that are used to find data that is stored in a two-dimensional plane. It only supports data that is stored in legacy coordinate pairs.
Sparse index is an optimized index which only contains pointers to documents that have value(s) in the indexed fields. For example, let's say you would like to add an index on lastname field
{ _id: 1, firstname: 'John', lastname: 'Black', age: 20 }
{ _id: 2, firstname: 'Stive', lastname: 'White', age: 17 }
{ _id: 3, firstname: 'Tom', age: 22 }
if you run
db.users.createIndex({ lastname: 1 });
command, it will add indexes on 3 documents, but you don't need to have an index on a document where is no lastname value (_id: 3); it's a waste of space and memory.
To avoid empty fields' indexing, mongodb has sparse
index, which is simply "check for non-empty value".
So when you add sparse: true
db.users.createIndex({ lastname: 1, sparse: true });
Mongodb will add indexes only for 2 documents (_id: 1, _id:2). Its great, but what if you want to index only those users' documents which are older than 18 years? You cant use sparse index because it only checks documents for value existence.
This is why partial indexes
were created.
db.person.createIndex(
{ age: 1},
{ partialFilterExpression: { age: { $gte: 18 }, lastname: { $exists: true }}
);
This example will put index only for 1 document(id: 1). Partial index is complex version of sparse, it will filter documents not only checking their existence, but using conditions provided in partialFilterExpression
field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With