9

From http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views

The couchdb reduce function is defined as

function (key, values, rereduce) {
    return sum(values);
}
  • key will be an array whose elements are arrays of the form [key,id]
  • values will be an array of the values emitted for the respective elements in keys
  • i.e. reduce([ [key1,id1], [key2,id2], [key3,id3] ], [value1,value2,value3], false)

I am having trouble understanding when/why the array of keys would contain different key values. If the array of keys does contain different key values, how would I deal with it?

As an example, assume that my database contains movements between accounts of the form.

{"amount":100, "CreditAccount":"account_number", "DebitAccount":"account_number"}

I want a view that gives the balance of an account.

My map function does:

emit( doc.CreditAccount, doc.amount )
emit( doc.DebitAccount, -doc.amount )

My reduce function does:

return sum(values);

I seem to get the expected results, however I can't reconcile this with the possibility that my reduce function gets different key values.

Is my reduce function supposed to group key values first? What kind of result would I return in that case?

JasonSmith
  • 72,674
  • 22
  • 123
  • 149
Alan
  • 2,140
  • 1
  • 24
  • 30

1 Answers1

3

By default, Futon "groups" your results, which means you get a fresh reduce per key—in your case, an account. The group feature is for exactly this situation.

Over the raw HTTP API, you will get one total reduce for all accounts which is probably not useful. So remember to use group=true in your own application to be sure you get summaries per account.

JasonSmith
  • 72,674
  • 22
  • 123
  • 149
  • Can you rely on getting all values in the key parameter with the same value of key in this case? – Alan May 04 '10 at 16:04
  • You *will* get all values in the result of your HTTP query. In other words, your balance will be correct. However you **can not** rely on all values being passed to your `reduce()` function in one shot. That is one of the major trade-offs of CouchDB. – JasonSmith May 04 '10 at 18:13
  • In other words, the function you stated will work because **assuming group=true** it will always accumulate for one account. When another account starts, the value will reset back to 0 for you. – JasonSmith May 04 '10 at 18:20