Creating TextIndex in Micronaut with reactive mongoDB

I’m afraid that Micronaut Data does not yet support automatic index creation based on annotations for MongoDB. Micronaut Data now simplifies only work with SQL databases.

But you can still create the index manually using MongoClient like this:

@Singleton
public class ProductRepository {

    private final MongoClient mongoClient;

    public ProductRepository(MongoClient mongoClient) {
        this.mongoClient = mongoClient;
    }

    public MongoCollection<Product> getCollection() {
        return mongoClient
            .getDatabase("some-database")
            .getCollection("product", Product.class);
    }

    @PostConstruct
    public void createIndex() {
        final var weights = new BasicDBObject("name", 10)
            .append("description", 5);

        getCollection()
            .createIndex(
                Indexes.compoundIndex(
                    Indexes.text("name"),
                    Indexes.text("description")
                ),
                new IndexOptions().weights(weights)
            )
            .subscribe(new DefaultSubscriber<>() {
                @Override
                public void onNext(String s) {
                    System.out.format("Index %s was created.%n", s);
                }

                @Override
                public void onError(Throwable t) {
                    t.printStackTrace();
                }

                @Override
                public void onComplete() {
                    System.out.println("Completed");
                }
            });
    }

}

You can of course use any subscriber you want. That anonymous class extending DefaultSubscriber is used here only for demonstration purpose.

Update: You can create indexes on startup for example by using @PostConstruct. It means to add all index creation logic in a method annotated by @PostConstruct in some repository or service class annotated by @Singleton, then it will be called after repository/service singleton creation.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top