@CompoundIndex not working in Spring Data MongoDB
Asked Answered
S

3

17

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?

Shorts answered 11/6, 2015 at 7:30 Comment(6)
Have you tried pastebin.com/PynPCgRY ?Gogol
I did now and it does not change the behavior...Shorts
Hi! May I ask you to post the whole application ? It would be great if you're able to provide the Spring context at least.Mcneely
I had the same problem, index was not created using the annotation, but it was created using ensureIndex explicitly. The i realised i was missing the Document annotaton. Now the index is created with the CompundIndex annotation.Seringapatam
I'm having the same problem right now in Spring Boot 1.4 with Spring Data Mongo 1.9.2 and the Mongo 3.2 java driver.Cohlette
Have you find an answer? my problem is #39848101Obscenity
P
17

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
Penuche answered 26/8, 2020 at 11:45 Comment(1)
4 years later and finding this bit of documentation is still difficult. but it fixed my problem - thank you!Buckden
C
5

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;
  }
}
Carder answered 25/7, 2022 at 19:51 Comment(1)
I tried both and each solution separately from @Ja'afar Naddaf and @Wiktor. But only Wiktor's solution works for me, It doesn't require spring.data.mongodb.auto-index-creation=true. I'm using spring-boot-starter-data-mongodb:3.1.9Kishakishinev
F
0

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/

Forgot answered 24/11, 2016 at 6:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.