与SQL COUNT(*)聚合函数对应的CouchDB是什么? [英] What is the CouchDB equivalent of the SQL COUNT(*) aggregate function?

查看:134
本文介绍了与SQL COUNT(*)聚合函数对应的CouchDB是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我是一位进入CouchDb Map / Reduce世界的SQL骑师(sorta)。我想我已经用以下方法弄清楚了CouchDB数据集的COUNT(*)SQL聚合函数的等效方式:

Yep, I'm a SQL jockey (sorta) coming into the CouchDb Map/Reduce world. I thought I had figured out how the equivalent of the COUNT(*) SQL aggregator function for CouchDB datasets with the following:

Map:

function(doc) {
  emit(doc.name, doc);
}

减少:

function(keys, values, rereduce){
  return values.length;
}

我认为可行,返回的内容如下:

Which I thought worked, returning something like:

"super fun C"   2
"super fun D"   2
"super fun E"   2
"super fun F"   18

...但并非如此。当我添加一条记录时,此计数变化很大。有时,计数实际上减少了,这非常令人惊讶。难道我做错了什么?也许我不太了解最终一致性的概念?

... but not really. When I add a record, this count varies wildly. Sometimes the count actually decreases, which was very surprising. Am I doing something wrong? Maybe I don't fully understand the concept of eventual consistency?

推荐答案

看来,您的简化结果正在减少。也就是说,对于每个键,多次调用 reduce ,然后使用这些结果再次调用。您可以使用 reduce 函数来解决此问题,例如:

It looks like your reduce results are being re-reduced. That is, reduce is called more than once for each key and then called again with those results. You can handle that with a reduce function like this:

function(keys, values, rereduce) {
  if (rereduce) {
    return sum(values);
  } else {
    return values.length;
  }
}

或者,您可以更改 map 函数,以便该值始终是文档计数:

Alternatively, you can change the map function so that the values are always a count of documents:

// map
function(doc) {
  emit(doc.name, 1);
}

// reduce
function(keys, values, rereduce) {
  return sum(values);
}

这篇关于与SQL COUNT(*)聚合函数对应的CouchDB是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆