Simply put I want to _sum
totals over a date range grouped by type. The original docs in the db are each for a single date, containing data by type. (For example, each doc has total apples, oranges, and pears picked on a date. We want to query for total apples, oranges, and pears picked over a date range.)
The "myview" map sends out
emit([date, type], values_array);
which I can query for date ranges as
..._view/myview?group=true&group_level=2&startkey=[20150501]&endkey=[20150530,{}]
and there lies the problem. It can give a sum for each date at group_level=1
, but I want to forget about the date at that point. I want to somehow re-key on type and then sum.
I think I need two views in succession for this, but not sure how to do that.
I accomplished this using a list function on the view. Here's the overview:
.../myview?startkey=20150101&endkey=20150130
My List function looks like this (based on this Q&A about grouping a javascript array by type):
The prior View should
emit
the date as the key, and a javascript object as the value. In this example, a row of the view should look like:"key":20150101, "value":{"type":"apple", "value1":28, "value2":0}
. If you are new to Couch, here is how you write yourmap
function (and don't use a reduce however tempted you may be to_sum
):Lastly, your query would look like this:
http://localhost:5984/dbname/_design/ddocname/_list/mylistname/myviewname?startkey=20150501&endkey=20150510
I am somewhat new to both Javascript and Couch, so feel free to take a whack at this code.