使用反应式mongoDB在Micronaut中创建TextIndex

问题描述

我在Micronaut应用程序中使用反应性mongoDB

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

尝试创建TextIndex并搜索自由文本功能

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

在春季数据中,我们有@TextIndexed(weight = 2)为该集合创建一个TextIndex,这在Micronaut应用程序中是等效的。

解决方法

恐怕Micronaut Data尚不支持基于MongoDB注释的自动索引创建。现在,Micronaut Data简化了仅适用于SQL数据库的工作。

但是您仍然可以像这样使用MongoClient手动创建索引:

@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");
                }
            });
    }

}

您当然可以使用所需的任何订户。扩展DefaultSubscriber的匿名类在这里仅用于演示目的。

更新:您可以在启动时创建索引,例如使用@PostConstruct。这意味着将所有索引创建逻辑添加到某个由@PostConstruct注释的存储库或服务类中由@Singleton注释的方法中,然后在创建存储库/服务单例之后调用它。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...