The GROUP BY parameter within SQL provides
summary information for a group of matching records according to
the specified fields, often for use with a numeric field for a
sum or total value, or count operation.
For example:
SELECT name,city,SUM(sales) FROM sales GROUP BY name,cityThis query groups the information by the two fields 'name' and 'city' and produces a sum total of these values. To translate this into a map/reduce function within Couchbase Server:
From the list of selected fields, identify the field used
for the calculation. These will need to be exposed within
the value emitted by the map()
function.
Identify the list of fields in the GROUP
BY clause. These will need to be output within the
key of the map() function.
Identify the grouping function, for example
SUM() or COUNT(). You
will need to use the equivalent built-in function, or a
custom function, within the reduce()
function of the view.
For example, in the above case, the corresponding map function
can be written as map():
function(doc, meta) { emit([doc.name,doc.city],doc.sales); }
This outputs the name and city as the key, and the sales as the
value. Because the SUM() function is used,
the built-in reduce() function
_sum can be used.
An example of this map/reduce combination can be seen in
Section 9.5.2.2, “Built-in _sum”.
More complex grouping operations may require a custom reduce function. For more information, see Section 9.5.2.4, “Writing Custom Reduce Functions”.