Query based on a variable


#1

I want to query couchbase on value of particular field. So, We have json documents called User in couchbase, and we want to get all User objects having name like “Smith”. The value “Smith” is a variable and injected by the user at run time. How can I send this variable to couchbase Map function from a java client?

User is like following:
{
“id”: 38383838,
“name”: “Smith”
“age”: 45

}

Thanks,


#2

Hi, you can get the documents by any field rather than key by creating the view on couchbase which has the key as your variable in emit function, then you can set key value on java code. for example

In view function

function (doc, meta) {
emit(doc.yourvaraible, null);
}

In java

View view = client.getView(designDocument, viewName);
Query query = new Query();
query.setIncludeDocs(true);
query.setKey(yourvaraible);
query.setDescending(true);
query.setStale(Stale.FALSE);
ViewResponse response = client.query(view, query);