Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Mongo @Indexed creates index multiple times

I'm using @Indexed annotation using Spring Data Mongo followed by @Document at a class level.

I notice from the logs that each time the connection to Mongo DB is established, a creation of the index is performed.

Is this normal behaviour and won't it create an overload on the Database?

Please make me understand the lifecycle of @Indexed annotation and is there any way possible to ignore the index creation if already created?

I'm unable to find anything documented for this.

like image 570
Adnan Avatar asked Sep 08 '25 08:09

Adnan


1 Answers

Using @Indexed ensures on the first access to an entity that declared indexes are created. Spring Data MongoDB's IndexOperations calls createIndex(…). Typically, this is a no-op once the index exists with the given specification. Typically applies to applications that start up and run for quite a while.

AWS Lambda rather cleans up instances that are not hot to free resources. I'm not sure how this affects MongoDB performance when you call e.g. createIndex(…) every minute or so. If you don't see a negative impact, then things might be fine.

Index creation on MongoDB prepares an exclusive lock (IX, intent to exclusively lock) and escalates that lock during index creation. This is can be an impact if sufficient processes try to call createIndex(…).

What are the alternatives?

  • Keep a persistent service instance (which contradicts AWS Lambda to some extent)
  • Remove @Indexed entirely and move index creation to an out of band process (Create the indexes externally)
  • Remove @Indexed and create indexes programmatically (This is the recommended approach giving you the most flexibility. You can check whether the required indexes are already present and skip index creation).

See also:

  • MongoDB db.collection.createIndex(…)
like image 51
mp911de Avatar answered Sep 09 '25 21:09

mp911de