2

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

3 Answers 3

1

"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));
  }
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

+1 thanks, an odd decision though. To make the default action of an annotation to do nothing is quite deceptive. I suspect a few people will add @Indexed expecting it to do what it says and not realise that it does nothing.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.