Spring & Couchbase - 如何通过代码创建索引

Spring & Couchbase - how to create indexes via code

我的 Spring 启动应用程序正在使用 Couchbase 5.1 社区。

我的应用程序需要一个主要索引和多个辅助索引。

目前,为了创建所需的索引,我访问 UI 和 query 页面并手动创建应用程序需要的索引 as described here

我一直在寻找一种通过代码自动执行此操作的方法,因此当应用程序启动时,它会检查索引是否丢失并在需要时创建它们。

有没有办法通过 Spring 数据或通过 Couchbase 客户端做到这一点?

您可以使用索引 class 中的 DSL 创建它们。在“Indexing the Data: N1QL & GSI

下的文档中有一个使用它的示例

来自那个例子:

You can also create secondary indexes on specific fields of the JSON, for better performance:

Index.createIndex("index_name").on(bucket.name(), "field_to_index")

In this case, give a name to your index, specify the target bucket AND the field(s) in the JSON to index.

如果索引已经存在,则会有一个 IndexAlreadyExistsException (see documentation),因此您需要检查一下。

所以我是这样解决的:

import com.couchbase.client.java.Bucket;

public class MyCouchBaseRepository{

private Bucket bucket;

public MyCouchBaseRepository(<My Repository that extends CouchbasePagingAndSortingRepository>  myRepository){
    bucket = myRepository.getCouchbaseOperations().getCouchbaseBucket();
     createIndices();
}


private void createIndices(){

   bucket.bucketManager().createN1qlPrimaryIndex(true, false)

   bucket.query(N1qlQuery.simple("CREATE INDEX xyz ON `myBucket`(userId) WHERE _class = 'com.example.User'"))
   ...       

}

}