计算某种类型的文档(之前针对用户进行过滤)
文件(伪,rev和id省略):
{
"type": 1,
"username": "aron",
"data": { ... }
}
{
"type": 1,
"username": "bob",
"data": { ... }
}
{
"type": 1,
"username": "steve",
"data": { ... }
}
{
"type": 1,
"username": "steve",
"data": { ... }
}
{
"type": 2,
"username": "steve",
"data": { ... }
}
{
"type": 3,
"username": "steve",
"data": { ... }
}
{
"type": 3,
"username": "steve",
"data": { ... }
}
{
"type": 3,
"username": "steve",
"data": { ... }
}
我想知道,steve有多少个1/2/3类型的文件。
查看:
count: {
map: function (doc) {
emit([doc.username, doc.type], 1);
}
reduce: function (key, values, rereduce) {
return sum(values);
}
}
现在我要求
/database/_design/myDesign/_view/count?key=["steve",1] // result: 2
/database/_design/myDesign/_view/count?key=["steve",2] // result: 1
/database/_design/myDesign/_view/count?key=["steve",3] // result: 3
这个工作得很好。
为了让事情变得更聪明,我想知道我是否可以在一个视图中查询它?
有没有一种方法可以统计一个视图中未知类型文档的数量?
Documents (pseudo, rev and id omitted):
{
"type": 1,
"username": "aron",
"data": { ... }
}
{
"type": 1,
"username": "bob",
"data": { ... }
}
{
"type": 1,
"username": "steve",
"data": { ... }
}
{
"type": 1,
"username": "steve",
"data": { ... }
}
{
"type": 2,
"username": "steve",
"data": { ... }
}
{
"type": 3,
"username": "steve",
"data": { ... }
}
{
"type": 3,
"username": "steve",
"data": { ... }
}
{
"type": 3,
"username": "steve",
"data": { ... }
}
I want to know, how many documents of type 1/2/3 steve has.
View:
count: {
map: function (doc) {
emit([doc.username, doc.type], 1);
}
reduce: function (key, values, rereduce) {
return sum(values);
}
}
Now I request
/database/_design/myDesign/_view/count?key=["steve",1] // result: 2
/database/_design/myDesign/_view/count?key=["steve",2] // result: 1
/database/_design/myDesign/_view/count?key=["steve",3] // result: 3
This works perfectly well.
To smart things up, I was wondering if I can query that in one view?
Is there a way to count the number of documents of unknown number of types in one view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用这样的正文发布到您的视图;
另外,尝试使用“_sum”作为你的reduce函数,它将在Erlang中本地运行,并且应该比在Javascript中快几倍。
You can POST to your view with a body like this;
Also, try using "_sum" as your reduce function, it will run natively in Erlang and should be several times faster than doing it in Javascript.
您可以执行范围查询来实现此目的:
这将为
["steve",1]
和["steve",3]
之间的每个键获取一行。您可以根据实际类型调整值0
和3
。例如,如果您的类型可以是任何标量值,则可以使用["steve",null]
和["steve",{}]
作为范围边界。You can perform a range query to achieve this:
This will fetch one line for every key between
["steve",1]
and["steve",3]
inclusive. You can adjust values0
and3
according to what your types can actually be. For instance, if your types can be any scalar value, you can use["steve",null]
and["steve",{}]
as the range boundaries.