Map Reduce query with a group by within a timestamp range


#1

I have a database with a “timestamp” (in milliseconds), a “type” String, and some other stuff.

The map function creates an array of “type” and “timestamp” and currently in that order.

What I’m trying to do is a map-reduce on a query where I group by on the “type” within a specific timestamp range. The range is usually n seconds ago. Per the instructions, I will not filter based on current time in the map function.

It’s a bit of a conundrum. If I try [timestamp, type], then group by doesn’t work because it creates one group for each unique pair. If I try [type, timestamp] with a startKey of ["", 30secondsAgo] and an endKey of [{}, now] the group by will work but the range does not work since the sort order is done by the first element of the array-key.

Any ideas on how to accomplish what I’m attempting?


#2

So if I understand correctly, you want to select results by time, but you want to sort and group them by type?

If so, you can’t do that in a basic query, because the view index is sorted by its key, and the query results will have the same ordering. You’d need to use the timestamp as the key, and then post-process the query results to sort them by type.

(If you’re using iOS, you can use the sortDescriptors property to do this post-sorting for you. This hasn’t been implemented on all platforms yet. It might be in Java in 1.0.4 but I’m not sure.)


#3

I’m on Android. I found a different way to achieve what I needed. Basically, the reducer ends up doing a sorts of grouping. It seems to work and should work even with a rereduce.

My solution was to return a map with the key as the “types” and the value as an array of reduced values. For instance [count, sum, product].

Thanks.