What is the CouchDB equivalent of the SQL COUNT(*) aggregate function?

前端 未结 2 701
-上瘾入骨i
-上瘾入骨i 2020-12-08 10:58

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 d

相关标签:
2条回答
  • 2020-12-08 11:28

    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;
      }
    }
    

    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);
    }
    
    0 讨论(0)
  • 2020-12-08 11:30

    In your reduce just put:

    _count

    You can also get a sum using:

    _sum

    so basically reduce: "_sum" or reduce: "_count" and make sure the value your map emits is a valid integer (numeric value)

    See "Built in reduce functions".

    0 讨论(0)
提交回复
热议问题