问题
Say I have a map that emits the following objects
{"basePoints": 2000, "bonusPoints": 1000}
{"basePoints": 1000, "bonusPoints": 50}
{"basePoints": 10000, "bonusPoints": 5000}
How could I write a reduce in Erlang (not javascript) that would return an aggregate object like this:
{"basePoints": 13000, "bonusPoints": 6050}
(I would rather not have to write 2 separate views that emits each value separately if I can help it)
Many Thanks!
回答1:
You actually do not need special reduce, in this case you can use standard _sum
, since it’s able to sum not only numbers, but also arrays of numbers.
Just emit [basePointsNum, 0]
for basePoints
and [0, bonusPointsNum]
for bonusPoints
. Or if you have both fields in one doc you might emit [basePointsNum, bonusPointsNum]
.
After reducing using built-in _sum
you will receive an array of two numbers, each is a sum of appropriate index column. This feature seems to be undocumented, however works for both CouchDB and PouchDB, and it’s blazing fast.
来源:https://stackoverflow.com/questions/50836544/couchdb-erlang-reduce-aggregate-object