If you have specified an array as your compound key within your
view, then you can specify the group level to be applied to the
query output when using a reduce().
When grouping is enabled, the view output is grouped according
to the key array, and you can specify the level within the
defined array that the information is grouped by. You do this by
specifying the index within the array by which you want the
output grouped using the group_level parameter.
You can see described in
Figure 9.14, “View Grouping”.
The group_level parameter specifies the array
index (starting at 1) at which you want the grouping occur, and
thgenerates a unique value based on this value that is used to
identify all the items in the view output that include this
unique value:
A group level of 0 groups by the entire
dataset (as if no array exists).
A group level of 1 groups the content by
the unique value of the first element in the view key array.
For example, when outputting a date split by year, month,
day, hour, minute, each unique year will be output.
A group level of 2 groups the content by
the unique value of the first and second elements in the
array. With a date, this outputs each unique year and month,
including all records with that year and month into each
group.
A group level of 3 groups the content by
the unique value of the first three elements of the view key
array. In a date this outputs each unique date (year, month,
day) grouping all items according to these first three
elements.
The grouping will work for any output structure where you have output an compound key using an array as the output value for the key.
When using grouping and selection using the
key, keys, or
startkey/endkey parameters,
they query value should match at least the format (and element
count) of the group level that is being queried.
For example, using the following map()
function to output information by date as an array:
function(doc, meta) { emit([doc.year, doc.mon, doc.day], doc.logtype); }
If you specify a group_level of
2 then you must specify a key using at
least the year and month information. For example, you can
specify an explicit key, such as [2012,8]:
?group=true&group_level=2&key=[2012,8]Or a range:
?group=true&group_level=2&startkey=[2012,2]&endkey=[2012,8]You can also specify a year, month and day, while still grouping at a higher level. For example, to group by year/month while selecting by specific dates:
?group=true&group_level=2&startkey=[2012,2,15]&endkey=[2012,8,10]
Specifying compound keys that are shorter than the specified
group level may output unexpected results due to the selection
mechanism and the way startkey and
endkey are used to start and stop the
selection of output rows.