Couchdb:在单个视图中过滤和分组 [英] Couchdb: filter and group in a single view

查看:71
本文介绍了Couchdb:在单个视图中过滤和分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Couchdb数据库,其文档格式为:{名称,时间戳,值}

I have a Couchdb database with documents of the form: { Name, Timestamp, Value }

我有一个视图,该视图显示按名称分组的摘要和值。这是直接的reduce函数。

I have a view that shows a summary grouped by name with the sum of the values. This is straight forward reduce function.

现在,我想过滤视图以仅考虑时间戳在给定范围内发生的文档。

Now I want to filter the view to only take into account documents where the timestamp occured in a given range.

AFAIK这意味着我必须在地图函数的发射键中包含时间戳,例如。 emit([doc.Timestamp,doc.Name],doc)

AFAIK this means I have to include the timestamp in the emitted key of the map function, eg. emit([doc.Timestamp, doc.Name], doc)

但是一旦我这样做, reduce函数不再看到分组在一起的行来计算总和。如果我先输入名称,则只能在1级进行分组,但是如何在2级进行过滤?

But as soon as I do that the reduce function no longer sees the rows grouped together to calculate the sum. If I put the name first I can group at level 1 only, but how to I filter at level 2?

有没有办法做到这一点?

Is there a way to do this?

推荐答案

我认为仅通过一次HTTP提取和/或在您自己的代码中没有其他逻辑就不可能做到这一点。

I don't think this is possible with only one HTTP fetch and/or without additional logic in your own code.

如果您 emit([时间,名称]),则可以查询 startkey = [timeA] & endkey = [timeB]& group_level = 2 来获取 timeA timeB 将时间戳名称相同的地方分组。然后,您可以对其进行后处理以在名称匹配时加起来,但是初始结果集可能比您要处理的大。

If you emit([time, name]) you would be able to query startkey=[timeA]&endkey=[timeB]&group_level=2 to get items between timeA and timeB grouped where their timestamp and name were identical. You could then post-process this to add up whenever the names matched, but the initial result set might be larger than you want to handle.

另一种方法是 emit([name,time])。然后,您可以先使用 group_level = 1 进行查询,以获取名称列表(如果您的应用程序尚不知道它们的名称)。然后,对于每个查询,您将查询 startkey = [nameN]& endkey = [nameN,{}]& group_level = 2 以获取每个名称的摘要。

An alternative would be to emit([name,time]). Then you could first query with group_level=1 to get a list of names [if your application doesn't already know what they'll be]. Then for each one of those you would query startkey=[nameN]&endkey=[nameN,{}]&group_level=2 to get the summary for each name.

(请注意,在我的查询示例中,我未对JSON开始/结束键进行编码,以使它们更易于阅读,但您需要应用您的语言在实际使用中相当于JavaScript的 encodeURIComponent 。)

(Note that in my query examples I've left the JSON start/end keys unencoded, so as to make them more human readable, but you'll need to apply your language's equivalent of JavaScript's encodeURIComponent on them in actual use.)

这篇关于Couchdb:在单个视图中过滤和分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆