Skip to content

Instantly share code, notes, and snippets.

@couchtim
Created August 17, 2012 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save couchtim/3375697 to your computer and use it in GitHub Desktop.
Save couchtim/3375697 to your computer and use it in GitHub Desktop.
Couchbase View query w/ Java: how to quote startkey?
/*
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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment