Liam
Liam

Reputation: 53

Java Spring MongoDB @TextIndexed annotation not creating index in existing db

I have collection in MongoDB and I'm trying to generate text indexes using Spring annotations (@TextIndexed). I'm not creating database on application start, it's already created.

Problem is - indexes are not being added to my database.

Does annotation work only when you creating database after starting application?

Thanks.

Spring v. 4.3.2 MongoDB v. 4.0.1

Upvotes: 2

Views: 1750

Answers (3)

skrymir1
skrymir1

Reputation: 607

With the most recent releases of Spring Boot, there should be a property spring.data.mongodb.auto-index-creation, which does all the magic. Even on existing databases and collections.

Upvotes: 0

amorenew
amorenew

Reputation: 10896

on the latest release, you should follow

@Configuration
public class Config extends AbstractMongoClientConfiguration {

    @Override
    protected boolean autoIndexCreation() {
        return true;
    }
    // ...
}

https://github.com/spring-projects/spring-data-mongodb/pull/845

Upvotes: 1

Juan Bermudez
Juan Bermudez

Reputation: 430

"Does annotation work only when you creating the database after starting application"?

The answer is yes.

If the collection is already created, Spring data does not initialize the indexes. I had to make something like you want to do and the only solution I found was to do it using the MongoOperations instance.

  @Autowired
  private MongoOperations mongoOps;

  @PostConstruct
  public void initializeIndexesInDb(){
    mongoOps.indexOps(YourDocumentClass.class).ensureIndex(new Index().on("fieldName", Direction.ASC));
  }

Upvotes: 1

Related Questions