在 CouchDB 中分别对一个视图中的两个值求和
Sum two values in one view separately in CouchDB
所以假设我在 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"
}
我想要的是对所有 nkill 和 nwound 值求和并得到类似这样的结果:
[1970, "Mexico","North America"] 4, 2
目前我只能对两个值之一或两个值求和,但这不是我想要的。
我的地图函数现在看起来像这样返回结果:
function(doc) {
if(doc.nkill >= 1) {
emit([doc.iyear,doc.country_txt,doc.region_txt],parseInt(doc.nkill));
}
}
我使用 _sum 作为 reduce 函数。
那个 returns 我的键和值是这样的:
[1970, "Mexico", "North America"] 4
使用自定义 reduce
函数代替 CouchDB 的内置 _sum
。
你可以在reduce
函数中传递一个数组或对象作为值,分别将两个值相加,然后输出新的array/object.
为了让reduce
函数可以消费一个对象(例如),map
函数应该改成这样:
function(doc) {
if(doc.nkill >= 1) {
emit([doc.iyear,doc.country_txt,doc.region_txt],
{nkill: parseInt(doc.nkill), nwound: parseInt(doc.nwound));
}
}
另一种方式
查看 CouchDB 文档后,the strong preference is to return scalar values from the reduce
function - or an array. This SO question 似乎涵盖了您的用例:如何分别对同一查询中的两个不同值求和。
所以假设我在 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"
}
我想要的是对所有 nkill 和 nwound 值求和并得到类似这样的结果:
[1970, "Mexico","North America"] 4, 2
目前我只能对两个值之一或两个值求和,但这不是我想要的。
我的地图函数现在看起来像这样返回结果:
function(doc) {
if(doc.nkill >= 1) {
emit([doc.iyear,doc.country_txt,doc.region_txt],parseInt(doc.nkill));
}
}
我使用 _sum 作为 reduce 函数。
那个 returns 我的键和值是这样的:
[1970, "Mexico", "North America"] 4
使用自定义 reduce
函数代替 CouchDB 的内置 _sum
。
你可以在reduce
函数中传递一个数组或对象作为值,分别将两个值相加,然后输出新的array/object.
为了让reduce
函数可以消费一个对象(例如),map
函数应该改成这样:
function(doc) {
if(doc.nkill >= 1) {
emit([doc.iyear,doc.country_txt,doc.region_txt],
{nkill: parseInt(doc.nkill), nwound: parseInt(doc.nwound));
}
}
另一种方式
查看 CouchDB 文档后,the strong preference is to return scalar values from the reduce
function - or an array. This SO question 似乎涵盖了您的用例:如何分别对同一查询中的两个不同值求和。