Photo by Maarten van den Heuvel on Unsplash
SpringPortal #5 - Optimizing APIs in Spring Boot
Optimizing APIs in Spring Boot using MongoDB index
Table of contents
MongoDB Indexes
MongoDB provides indexes to support efficient querying. Without indexes, all the documents are scanned for the required query, resulting in high resource usage.
These indexes can be used to optimize our APIs.
Normal Index
- MongoDB query without the index
MongoDB query with the index
Creating the index
Searching Again
An ascending index on price has reduced the load on MongoDB and will vastly improve the API response time.
Text Index
- While working with text like searching for a substring on a field, searches become complicated and time-consuming.
- We can add a simple field index like in the earlier example.
- Searching using regex:
- This query has taken 3 ms to complete.
- But if we have several records, then this will be very slow, taking up to even several minutes.
- If we create a simple index on the field,
- This index will speed up the query.
- But as soon as we racked up to some millions of records, this index will also start to fail to give us desired results.
For this kind of situation where we dealing with a String field in MongoDB, we have the
$text
index.Creating the index
Try the search
One caveat during index creation.
- MongoDB supports specific languages only.
- You can find the list here - (MongoDB Supported languages)[mongodb.com/docs/manual/reference/text-sear..
So, if you try to create an index while using an unsupported language, then MongoDB will throw an error.
- "Index build failed: 165f5364-de51-4340-8187-3a6fb4d5c089: Collection springportal-db.listingsAndReviews ( 83453648-7574-422a-900b-7ba719b4b36b ) :: caused by :: language override unsupported: hindi"
To overcome this error we can create the index using the Compass MongoSH
db.listingsAndReviews.createIndex({ 'summary': 'text' }, { default_language: "none", language_override: "none" })
This will help us to overcome the error and create the index even when using the unsupported language.
Conclusion
There is a lot to do when trying to optimize an API and optimizing the database calls is one part of it. MongoDB indexes are great to come closer to our goal.