Couchbase: Quering data bucket with Partial id.

Table of contents
Reading Time: 2 minutes


In this article I am going to explain how to get documents from data bucket, if you only have partial Id, in other words using LIKE operation of Sql in couchbase by using Views of Couchbase.

For Example:

I have these four documents in my bucket, and I want to get all the documents having starting “abc”, then it must retrieve all the three documents.

Screenshot from 2015-07-07 13:36:18

Result must contain all the three documents :

abc::1, abc::2, abc::3

Then to implement this we can use the View functionality of Couchbase, and then we can fire the query on the view accordingly.

Step 1: Create view on the data bucket, by clicking on create Development View in View option.

Step 2 : Edit the function of view accordingly :

function (doc, meta) {

You can use different functions like emit() in this function accordingly and the list of functions can be found here.

Its result can be seen using Show Result

Screenshot from 2015-07-07 13:57:04

Step 3: Now in your code firstly to enable queries you need to enable them

System.setProperty(“com.couchbase.queryEnabled”, “true”)

Step 4:

Now run the query to get the output having your required value in key and you can perform function startKey() on that.

val queryResult = openedBucket.get.query(ViewQuery.from("dev_name", "name").startKey("abc::").stale(Stale.FALSE))
val totalResult=queryResult.allRows

Here startKey(dynamicKey: String) is performed on key returned from that function in view, and stale.FALSE is written so the view gets updated each and every time.

Now it returns an object of List[ViewRow] and you can perform different operations accordingly on the result.