Grouping via Java sdk


Hello, need a little guidance

I am currently on sdk 1.x with couchbase 3.x.

I have a large dataset such as

Item {
String category;
Integer value;

I’d like to group by category and find min of the value.

I created a map and reduce but not sure how to access the data via the sdk.



can you quickly tell what you used as map and reduce functions?



function (doc, meta) {
if (doc && doc.docType == ‘PRODUCT’, doc.category) {
if (doc.value != null)
emit(doc.category, doc.value);


when I do this using web console and Show Results, I get null for key and stats for value, then I select group, and I get my categories for key, and stats for value, but don’t know how to access the reduce data via SDK.



Taking your example and assuming you have category “apple”, with the minimum value for every apple at 120

You can use grouping like this in the java SDK:

ViewResult result = bucket.query(
    ViewQuery.from("myDesignDoc", "myViewName")
   //activate level 1 grouping

List<ViewRow> rows = result.allRows();
ViewRow firstRow = rows.get(0);
//using _stats with grouping will implicitely reduce, return a JsonObject for "value()"
System.out.println(firstRow.key() + ": " + ((JsonObject) firstRow.value()).getInt("min"));
//prints: apple: 120


Would this be latest version of the sdk ? I am currently on 1.x, via Spring data?


ah yes that’s with the latest SDK, worth mentioning you were using Spring Data 1.4.x since it doesn’t have any particular support for grouping and reduce…

You can execute a view query using the CouchbaseTemplate.queryView method, but the old client implies more work to achieve that because it doesn’t have any built-in JSON support, so the value it returns will be a plan raw JSON String.
Up to you to deserialize it using your JSON library of choice (or even searching in the String). Here is the example transposed to old client going through Spring Data’s template:

Query query = new Query();

ViewResponse result = couchbaseTemplate.queryView("myDesignDoc", "myViewName", query);
for (ViewRow viewRow : result) {
    System.out.println(row.getKey() + ": " + row.getValue()); //getValue returns a String, always

Will print:

apple: {"sum":579,"count":2,"min":123,"max":456,"sumsqr":223065}
banana: {"sum":3,"count":1,"min":3,"max":3,"sumsqr":9}


Great thanks, I will likely upgrade to the latest, but good to see both examples.

I tried using Query object although don’t recall if I tried setting group = true or reduce either way I got an error via spring that group/reduce wasn’t supported.