Fynn
Fynn

Reputation: 4873

@CompoundIndex not working in Spring Data MongoDB

I am working on an application using Spring Data MongoDB. I would like to create a compound index on one of my models. I have added a @CompoundIndex annotation at the top like so:

@Document
@CompoundIndexes({
    @CompoundIndex(name = "name_", def = "{ 'tenantId': 1, 'name': 1 }", unique = true)
})
public class MyModel {

}

However, the index is not created. I have also tried to directly place the @CompoundIndex above the class. The collection is still missing the index. The same index definition is working fine when created like so:

mongoTemplate.indexOps(MyModel.class).ensureIndex(new Index().named("name_").on("tenantId", Direction.ASC).on("name", Direction.ASC).unique());

I'd prefer to use the annotation-based definition of the index. Any ideas why this is not working?

Upvotes: 17

Views: 8742

Answers (3)

Wiktor
Wiktor

Reputation: 183

Couple years later, I faced the same issue. If none of above answers work for you (just like for me), try overriding autoIndexCreation() in MongoConfig class.

@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
  @Override
  protected boolean autoIndexCreation() {
    return true;
  }
}

Upvotes: 5

Ja'afar Naddaf
Ja'afar Naddaf

Reputation: 402

You need to add the following to application.properties:

spring.data.mongodb.auto-index-creation=true

or in application.yml:

spring:
  data:
    mongodb:
      auto-index-creation: true

Upvotes: 18

Waheed
Waheed

Reputation: 638

In this case I would rather go with mongodb createIndex method as it ensures indexes have been created, even if you created them in your app models (Spring boot in this case) it's always better to do a double check and create them manually https://docs.mongodb.com/v3.2/reference/method/db.collection.createIndex/

Upvotes: 0

Related Questions