Spring Data Mongo @Indexed creates index multiple times

Viewed 2806

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.

3 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:

from version 2.2.x, you can control the behavior of creating indexes on server startup using property called - spring.data.mongodb.autoIndexCreation: true/false

As i know, what ever you do, the application call the command to create Index (new or already exit). And this process is good for an application to run and make sure everything. About what this command do in MongoDb, let check it out more

  1. What does Index do and how can this work (https://en.wikipedia.org/wiki/Database_index) Sort: Make a copy and give this an order (everything with rules will help to speed-up the search speed) May be it is a B-Tree or other structure

  2. What will the command createIndex do? https://jira.mongodb.org/browse/SERVER-12699 https://jira.mongodb.org/browse/SERVER-10879 Those two question make this clear, it won't do the same thing already exit. So the logic is simple.

Application: I want some thing (create index and make sure it will be there) ~> I should call the CreateIndex

MongoDb: Take the command: - I see it is new: create it - I see it duplicate: Oh dump action, i will skip this and let you know.

It's my quick-research about this problem

Related