Solaiman
Solaiman

Reputation: 318

Sum two values in one view separately in CouchDB

So Assume I have the following two documents in CouchDB:

{
   "_id": "197000000002",
   "_rev": "1-fbe819b01108f30d2e9e96f3fb46eff8",
   "iyear": "1970",
   "region_txt": "North America",
   "country": "130",
   "region": "1",
   "country_txt": "Mexico",
   "nkill": "1",
   "nwound": "1",

}

{
       "_id": "197000000003",
       "_rev": "1-fbe819b01108f30d2e9e96f3fb46eff8",
       "iyear": "1970",
       "region_txt": "North America",
       "country": "130",
       "region": "2",
       "country_txt": "Mexico",
       "nkill": "3",
       "nwound": "1"
    }

What I want is to SUM all the nkill and nwound values and have something like this:

[1970, "Mexico","North America"]    4, 2

At this moment I am only able to SUM one of the two values or both combined, but that is not what I want.

My Map Function now looks like this returned as result:

function(doc) {
    if(doc.nkill >= 1) {
        emit([doc.iyear,doc.country_txt,doc.region_txt],parseInt(doc.nkill));
    }
}

And I use _sum for the reduce function.

That returns me a key and value like this:

[1970, "Mexico", "North America"]   4

Upvotes: 1

Views: 123

Answers (1)

tephyr
tephyr

Reputation: 1051

Use a custom reduce function instead of CouchDB's built-in _sum.

You may pass an array or object as the value in the reduce function, separately sum the two values, then output the new array/object.

So that the reduce function can consume an object (for example), the map function should be changed to something like:

function(doc) {
    if(doc.nkill >= 1) {
        emit([doc.iyear,doc.country_txt,doc.region_txt],
            {nkill: parseInt(doc.nkill), nwound: parseInt(doc.nwound));
    }
}

A different way

After looking over the CouchDB docs, it appears that the strong preference is to return scalar values from the reduce function - or an array. This SO question covers your use case: how to separately sum two different values from the same query.

Upvotes: 0

Related Questions