Couchdb: filter and group in one view

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

I have a view that shows a summary grouped by name with a sum of values. This is a direct reduction in function.

Now I want the filter to display only documents that have a timestamp in a given range.

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

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

Is there any way to do this?

+4
source share
2 answers

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

If you are emit([time, name]) , you can query startkey=[timeA]&endkey=[timeB]&group_level=2 to get the elements between timeA and timeB grouped, where their timestamp and name were identical. You can then post-process this to compose them when the names match, but the original result set may be larger than you want to process.

An alternative would be emit([name,time]) . You can then query first with group_level=1 to get a list of names [if your application does not already know what they will be]. Then, for each of them, you request startkey=[nameN]&endkey=[nameN,{}]&group_level=2 to get a summary for each name.

(Note that in my sample requests, I left unencrypted JSON start / end keys to make them more human readable, but you need to apply your equivalent JavaScript encodeURIComponent to them in actual use.)

+1
source

You cannot pretend a presentation. You need to write another picture of the map, which has filtering and makes grouping at the end. Sort of:

 map: function(doc) { if (doc.timestamp > start and doc.timestamp < end ) { emit(doc.name, doc.value); } } reduce: function(key, values, rereduce) { return sum(values); } 

I suppose you cannot save this view and should specify it as a special request in your application.

-2
source

Source: https://habr.com/ru/post/1333092/


All Articles