On 22 Nov 2008, at 18:19, Jedediah Smith wrote:

Let's say I have a couchdb full of documents representing transactions e.g.

{
 type: "transaction",
 account: "bob",
 date: "2008-11-22 21:01:00",
 amount: 123.45
}

where amount can be positive or negative, representing a credit or debit respectively

I want a view of balance by account and date i.e. given an account and date, get the sum of all transaction amounts for that account, up to that date.

map: function(doc) {
  emit(doc.date, doc.amount);
}

reduce function(key, values) {
  return sum(values):
}

If you query `_view/viewname`, you get the total sum of all `doc.amount` instances.

If you are using [2008, 11, 22, 21, 01, 00] for the date you can do:

 - query `_view/viewname?group_level=1` to get all amounts per year
 - query `_view/viewname?group_level=2` to get all amounts per months
 - etc...

I assume though you want to be able to get these values per `doc.account`. For this, do

map: function(doc) {
  emit([doc.account, doc.date], doc.amount);
}

reduce: same as above.

Query with `_view/viewname?startkey=["bob", null]&endkey=["bob", {}]` to get all data for bob. Use `group_level` as above. Substitute `null` and `{}` with dates to get amounts in a key-range.

Cheers
Jan
--



Can this be done with only a couchdb view while meeting these requirements:

- no client logic
- no storing intermediate data in documents
- optimal use of incremental view updates (adding/updating a transaction only invalidates view rows with same or later date)

If not, what's the best compromise that minimizes client logic?


Reply via email to