Search code examples
javaspring-bootspring-datacouchbasesql++

Spring & Couchbase - how to create indexes via code


My Spring Boot app is using Couchbase 5.1 community.

My app needs both a primary & several secondary indexes.

Currently, in order to create the needed indexes, I access the UI and the query page and manually create the indexes that the app needs as described here.

I was looking for a way to do it automatically via code, so when the app is starting, it will check if the indexes are missing and will create them if needed.

Is there a way to do it via Spring Data or via the Couchbase client?


Solution

  • So this is how I solve it:

    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'"))
       ...       
    
    }
    
    }