Search code examples
couchbasecouchbase-viewcouchbase-java-api

How do I create a View from couchbase Java sdk 2.1


I need to create a view with a map function ex:

function(doc, meta) {
  if(doc.docType == "testDoc")
    emit(meta.id, doc)
}

I have to create this view using couchbase java client 2.1.I could not find any thing in the documentation thanks


Solution

  • Here is some code to create a design document:

    List<View> viewsForCurrentDesignDocument = new ArrayList<View>();
    DesignDocument designDocument = DesignDocument.create("my_design_doc", viewsForCurrentDesignDocument);
    

    And add a view:

    String mapFunction =
        "function (doc, meta) {\n" +
        "  if(doc.docType == \"testDoc\") {\n" +
        "    emit(meta.id, doc);\n" +
        "  }\n" +
        "}";
    
    String reduceFunction = "..."  // or null if no reduce
    
    View v = DefaultView.create("my_view", mapFunction, reduceFunction);
    viewsForCurrentDesignDocument.add(v);
    bucket.bucketManager().insertDesignDocument(designDocument);
    

    You can check the API reference for more options(development mode, timeout, ...).