public
Created

Couchbase View query w/ Java: how to quote startkey?

  • Download Gist
gistfile1.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
/*
export CLASSPATH
CLASSPATH=`echo 1.1/*.jar | tr \ :`:
javac CouchbaseView/App.java
java CouchbaseView.App
*/
 
package CouchbaseView;
 
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.protocol.views.*;
 
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class App {
public static void main(String args[]) {
String key = "key";
String value = "Hello World";
if (args.length > 0) { key = args[0]; }
if (args.length > 1) { value = args[1]; }
 
CouchbaseClient cbc;
try {
List<URI> baseURIs = new ArrayList<URI>();
baseURIs.add(new URI("http://10.4.2.13:8091/pools"));
 
cbc = new CouchbaseClient(baseURIs, "default", "");
 
View view = cbc.getView("dev_my_app", "by_level");
 
Query myQuery = new Query();
/* This works from the shell, but how to get Java to quote OK?
 
$ curl 'http://10.4.2.13:8092/default/_design/my_app/_view/by_level?startkey=%5B"Level+2"%5D&endkey=%5B"Level+3"%5D'
{"total_rows":12,"rows":[
{"id":"eeeee==2222--11","key":["Level 2","ERRORED",1,"DIAPERS"],"value":12},
{"id":"wrwtwt==474--2","key":["Level 2","WAITING",1,"CPS_DEV32"],"value":12}
]
}
 
I get the following output when I run the program:
Query string '?startkey="%5B"Level+2"%5D"'
Error testing Couchbase: java.lang.RuntimeException: Failed to access the view
*/
myQuery.setRangeStart("%5B\"Level+2\"%5D");
System.err.println("Query string '" + myQuery + "'");
 
ViewResponse queryResults = cbc.query(view, myQuery);
Iterator<ViewRow> walkthrough = queryResults.iterator();
 
System.err.println("Found " + queryResults.size() + " docs.");
while (walkthrough.hasNext()) {
ViewRow row = walkthrough.next();
System.err.println("id: " + row.getId()
+ ", info: " + row.getKey()
+ ", score: " + row.getValue()
);
}
 
System.exit(0);
} catch (Exception e) {
System.err.println("Error testing Couchbase: " + e);
System.exit(1);
}
 
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.