Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 702
riorio Avatar asked Feb 05 '26 08:02

riorio


2 Answers

You can create them by using the DSL from the index class. There's an example of using it in the documentation under "Indexing the Data: N1QL & GSI"

From that example:

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.

If the index already exists, there will be an IndexAlreadyExistsException (see documentation), so you'll need to check for that.

like image 80
Matthew Groves Avatar answered Feb 07 '26 00:02

Matthew Groves


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

}

}
like image 44
riorio Avatar answered Feb 07 '26 01:02

riorio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!