CouchDB View equivalent of SUM & GROUP BY

邮差的信 提交于 2019-12-18 04:17:10

问题


I have multiple CouchDB documents representing a timestamp with a property userId and tag (a user can have n timestamps and assign each one a tag). I want to query CouchDB by a specific userId and get a sorted list of tags the user has used (sorted by occurrence).

How would the view look like?

If I want to get a list of all tags sorted by occurrence (no matter from which user) or if I assume that there are only documents with the same userId, I would make it like so:

Map:

function(doc) {
  if(doc.tag) emit(doc.tag, 1); 
}

Reduce:

function(keys, values) {
  return sum(values);
}

But how do I group the result so that I can filter the query by a specific userId?


回答1:


Answering my own question.

Seems like CouchDB supports arrays as keys. With that in mind it's pretty simple:

Map:

function(doc) {
  if(doc.tag) emit([doc.userId, doc.tag], 1); 
}

Reduce:

function(keys, values) {
  return sum(values);
}

The result is then sorted by userId & tag.



来源:https://stackoverflow.com/questions/5511810/couchdb-view-equivalent-of-sum-group-by

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!