riorio
riorio

Reputation: 6816

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?

Upvotes: 3

Views: 1703

Answers (2)

riorio
riorio

Reputation: 6816

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

}

}

Upvotes: 1

Matthew Groves
Matthew Groves

Reputation: 26141

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.

Upvotes: 2

Related Questions