Indexes are crucial for optimizing query performance, but they can also be very costly to create (meaning they can take a lot of CPU, especially if built from scratch on existing data.)
So, what if you’re uncertain about removing one? MongoDB offers a nifty solution: hiding indexes.
Understanding Hidden Indexes
Before bidding adieu to an index, you will likely want to conduct a thorough assessment of its impact. To make this easier MongoDB allows you to “hide” an index, essentially rendering it invisible to the query planner. However, the index remains intact within the database, providing an excellent opportunity for running test queries to gauge its significance before making a final decision.
To hide an index, execute the following command:
> db.collection.hideIndex("index_name")
Upon running getIndexes()
, you’ll still spot the index, albeit with a hidden attribute set to true
. This lets us know that the query planner won’t consider it for query optimization.
Unveiling Hidden Indexes
Should you wish to reintroduce the index to the query planner’s scrutiny, MongoDB equips you with a straightforward remedy:
> db.collection.unhideIndex("index_name")
Once revealed, the index seamlessly resumes its role in query optimization. In fact, the index’s maintenance persists even while it’s hidden, ensuring it can be promptly employed by the query planner upon restoration.
Important Considerations
It’s worth noting that hiding a TTL (Time-To-Live) index doesn’t exempt it from its intended functionality. Even when hidden, documents subject to TTL indexing will be purged upon expiration.
Conclusion
MongoDB’s hidden index feature can be a valuable tool for fine-tuning performance without committing to irreversible actions. By concealing indexes temporarily, administrators can evaluate their impact on query execution before making informed decisions.