javaindexingcouchbasecouchbase-java-api

How to create and publish Index using Java Client Programatically


Is it possible to programmatically create and publish secondary indexes using Couchbases Java Client 2.2.2? I want to be able to create and publish my custom secondary indexes Running Couchbase 4.1. I know this is possible to do with Couchbase Views but I can't find the same for indexes.


Solution

  • couchbase-java-client-2.3.1 is needed in order to programmatically create indexes primary or secondary. Some of the usable methods can be found on the bucketManger same that is used to upsert views. Additionally the static method createIndex can be used it support DSL and String syntax

    There are a few options to create your secondary indexes.

    Option #1:

    Statement query = createIndex(name).on(bucket.name(), x(fieldName));
    N1qlQueryResult result = bucket.query(N1qlQuery.simple(query));
    

    Option #2:

    String query = "BUILD INDEX ON `" + bucket.name() + "` (" + fieldName + ")";
    N1qlQueryResult result = bucket.query(N1qlQuery.simple(query));
    

    Option #3 (Actually multiple options here since method createN1qlIndex is overloaded

    bucket.bucketManager().createN1qlIndex(indexName, fields, where, true, false);