Search code examples
javamicronautmicronaut-data

Creating TextIndex in Micronaut with reactive mongoDB


I am using reactive mongoDB with Micronaut application

implementation("io.micronaut.mongodb:micronaut-mongo-reactive")

Trying to create a TextIndex and search Free text functionality

public class Product {
    @BsonProperty("id")
    private ObjectId id;
    private String name;
    private float price;
    private String description;
}

In spring data we have @TextIndexed(weight = 2) to create a TextIndex to the collection, what is the equivalent in the Micronaut application.


Solution

  • 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.