Hello.

I'm learning couchdb and I'd appreciate if someone could have look and
comment on the code and description that follows.

Given a set of documents like {date:"2009-10-11", amount:10500}, I'm
using the view below
and group_level={1,2,3} to group by year, month or day and return the
average amount for each group.

I don't think it's possible to write a rereduce-friendly averaging
function; Instead, I return an object
that holds the total amount and  the number of rows for each group.The
client has to calculate the average on his own.

_view/by_date?group_level=1 returns one row for each year, with the
average amount for that year
_view/by_date?group_level=2 returns one row for each mont, with the
average amount for that month
_view/by_date?group_level=3 returns one row for each day

//map.js:
function(doc) {
        emit(doc.date.split('-'), doc.amount);
}

// reduce.js
function(keys, values, rereduce) {
        if (rereduce) {
                var result = {tot:0, count:0};  
                for (var idx in values) {
                        result.tot += values[idx].tot;
                        result.count += values[idx].count;
                }
                return result;
        }
        else {
                var result = {tot:sum(values), count:values.length};
                return result;
        }
}

Thanks :)

-- 
:Matteo Caprari
[email protected]

Reply via email to