CouchDB View相当于SUM&通过...分组 [英] CouchDB View equivalent of SUM & GROUP BY
问题描述
我有多个CouchDB文档,它们代表带有属性userId和标签的时间戳(用户可以具有n个时间戳,并为每个标签分配一个标签)。我想通过特定的userId查询CouchDB并获取用户已使用的标签的排序列表(按出现的顺序排序。)。
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).
视图的外观如何?
如果我想获得一个按出现的顺序排列的所有标签的列表(无论来自哪个用户),或者如果我假设只有具有相同userId的文档,我会像这样:
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:
地图:
function(doc) {
if(doc.tag) emit(doc.tag, 1);
}
减少:
function(keys, values) {
return sum(values);
}
但是如何对结果进行分组,以便可以按
But how do I group the result so that I can filter the query by a specific userId?
推荐答案
回答我自己的问题。
好像CouchDB支持将数组作为键。考虑到这一点,这很简单:
Seems like CouchDB supports arrays as keys. With that in mind it's pretty simple:
地图:
function(doc) {
if(doc.tag) emit([doc.userId, doc.tag], 1);
}
减少:
function(keys, values) {
return sum(values);
}
然后按userId&标签。
The result is then sorted by userId & tag.
这篇关于CouchDB View相当于SUM&通过...分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!