SpringPortal #5 - Optimizing APIs in Spring Boot

Optimizing APIs in Spring Boot using MongoDB index

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.

Indexes are special data structures that store a small portion of the collection's data set in an easy-to-traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field.

These indexes can be used to optimize our APIs.

Normal Index

  • MongoDB query without the index

image.png

  • MongoDB query with the index

    1. Creating the index image.png

    2. Searching Again image.png

  • 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: image.png
    • 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, image.png
  • 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.

    1. Creating the index image.png

    2. Try the search image.png

    3. 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" image.png
      • To overcome this error we can create the index using the Compass MongoSH

        • db.listingsAndReviews.createIndex({ 'summary': 'text' }, { default_language: "none", language_override: "none" })
      • image.png
    4. 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.


GitLab

Code Repository

Article-specific commit

Did you find this article valuable?

Support Naman Jain by becoming a sponsor. Any amount is appreciated!