Java – Spring & Couchbase – How to create indexes from code

Spring & Couchbase – How to create indexes from code… here is a solution to the problem.

Spring & Couchbase – How to create indexes from code

My Spring Boot application uses the Couchbase 5.1 community. p>

My app needs a primary index and multiple secondary indexes.

Currently, in order to create the required indexes

, I go to the UI and query page and manually create the indexes required by the application as described here .

I’ve been looking for a way to do this automatically through code, so when the app starts, it checks if indexes are missing and creates them when needed.

Is there a way to do this through Spring Data or the Couchbase client?

Solution

You can create them using a DSL in an index class. In “ Indexing the Data: N1QL & GSI There is an example of using it in the documentation under “

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, the IndexAlreadyExistsException ( See documentation), so you’ll need to check it out.

Related Problems and Solutions