I'm using Cloudant (which is based on CouchDB) to store some data and want to create a reduce function to sum everything by key. I'm using the following mapping function:
function (doc) {
emit(doc.name, 1);
}
Therefore, I'm receiving a json
file like this:
{
"total_rows": 3,
"offset": 0,
"rows": [
{
"id": "605b21a9c295ec9c03ae2a6aadeb1422",
"key": "foo",
"value": 1
},
{
"id": "cb4258669082efeae9391288eb684339",
"key": "foo",
"value": 1
},
{
"id": "f2e7e69d6a3d26fa3b8cad1f0c63ccc3",
"key": "bar",
"value": 1
}
]
}
Therefore, for the _sum
built-in function I was expecting something like:
{
"rows": [
{
"key": "foo",
"value": 2
},
{
"key": "bar",
"value": 1
}
]
}
But I'm getting this:
{
"rows": [
{
"key": null,
"value": 3
}
]
}
I was reading the Cloudant documentation and found that the _sum
function:
Produces the sum of all values for a key, values must be numeric
But the result is not returning by key
, but every value
on my map.
You forgot to set the reduce query parameters.
I used the same map function + _sum function.
URL : http://host:5984/db/_design/stack/_view/byname?reduce=true&group=true
Result :
{"rows":[
{"key":"bar","value":1},
{"key":"foo","value":2}
]}