The Developer 2/2013

Page 38

To group and count the results, a reduce function is applied to the output of the map function. In Couchbase, three built in reduce functions are supplied. It is rare that one would write a custom reduce function, but it may be done. To get a count of breweries in a particular city, the built in count function is used. This function is expressed in a single call and will be fed the output of the map function above. _count

Applying this reduce function to the map output results in an index with aggregate data. {"rows":[ {"key":["Argentina","Buenos Aires","San Martin"],"value":1}, {"key":["Australia","New South Wales","Camperdown"],"value":1}, {"key":["Australia","New South Wales","Sydney"],"value":3}, {"key":["Australia","NSW","Picton"],"value":1}, ‌ ] }

When this view was queried, a group parameter was applied to provide grouped results. Additionally, a group level parameter may be used to group at a higher level. var view = client.GetView("breweries", "by_location").Group(true);

Having applied a group level of 2, this aggregation result did not consider the city. {"rows":[ {"key":["Argentina","Buenos Aires"],"value":1}, {"key":["Australia","New South Wales"],"value":4}, {"key":["Australia","NSW"],"value":1}, {"key":["Australia","Queensland"],"value":1}, ‌ ] }

The .NET SDK has a method for applying group levels.

var view = client.GetView("breweries", "by_location").Group(true).GroupAp(2);

The final query to examine is a bit more complex and addresses the master-detail pattern. Imagine the union of BREWERY and BEER rows, where the parent (brewery) row is followed immediately by its details (beers). To discriminate the breweries from beers, a second column is added. Brewery documents are marked with a 0 and beer documents a 1.

38


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.