【问题标题】:creating view with couchdb that does grouping and unique counting使用进行分组和唯一计数的 couchdb 创建视图
【发布时间】:2013-07-18 07:33:40
【问题描述】:

你好,我有这样的文件

{ 
  domains: "domain1.com", 
  ip: "192.168.0.1" 
}

文档可能有不同或重复的域/ips

我想要一个视图,给我一个列表

domain1 => 该域的唯一 IP 计数
domain2 => 该域的唯一 IP 计数
等等。

我知道如何获得:

domain => 使用此 map/reduce 的 ip 计数:

 "map": "function(doc) { emit(doc.domains, 1) }",<br/>
 "reduce": "_sum"

还有一个 group=true 参数

但我不知道如何获得:

域 => 唯一 ip 计数样式列表

为任何帮助干杯,对不起我的英语

【问题讨论】:

  • 我不认为它可以与 just 一个 map/reduce 视图一起使用,但是如果你将它与一个列表函数结合使用它应该是微不足道的。
  • 谢谢,如果涉及到一个列表,对我来说并不重要,我实际上也看过这个,只是在这一点上不知道如何完成它。

标签: mapreduce couchdb


【解决方案1】:

写一个只有map函数没有reduce函数的视图

function(doc) {
  if (doc.domains) emit(doc.domains, doc.ip);
}

然后创建一个计算唯一条目的列表函数。

function(head, req) {
  var ips = new Array();
  while (row = getRow()) {
    if (ips.indexOf(row) != -1) { 
      ips.push(row.value);
    }
  }
  send(ips.length);
}

警告:代码未经测试,可能包含错误。

最后,您在地图视图上调用列表函数,并将key 设置为您想要的域。请注意,如果每个域有大量 IP,此解决​​方案的效果将不会很好。

【讨论】:

    【解决方案2】:

    正如 Kim 所说,使用 CouchdDB 的 Map/Reduce 完成所有工作几乎是不可能的(或者可能使用非常棘手的 reduce 函数)。

    但是,您至少可以使用 Map/Reduce 执行重复数据删除部分,以获得比使用 Kim 的解决方案更好的性能。

    所以,首先使用map 来索引(域,ip)对(值不重要):

    function(o) {
      emit([o.domain, o.ip], null);
    }
    

    然后reduce 使用内置函数:

    _count
    

    现在,使用 list 来计算唯一 ips:

    function(head, req) {
      var domains = {};
      while (row = getRow()) {
        var d = row.key[0];
        if (d in domains) {
          domains[d]++;
        } else {
          domains[d] = 1;
        }
      }
      send(JSON.stringify(domains));
    }
    

    调用时,用group=true查询。

    注意:我还没有测试过列表的代码,所以你可能需要稍微修改一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多