Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range Keys in CouchDB Views

Tags:

couchdb

I'm using CouchDB for storing data about events. Each event has a start date/time and end date/time. I'd like to create a view now, that allows me to get a list of all events that happen on a specific date/time. But the events don't have a single dates, they can rather range over several days.

Now I don't know how I can reflect this in my view function. Unfortunately, I need granularity on minute level, so emitting a key for each minute might not be a valid solution. So how can I do that?

Thanks in advance!

like image 411
b_erb Avatar asked Jun 20 '10 11:06

b_erb


1 Answers

Ok, here's a solution anyway! I just ping-ponged with Jan (Lehnardt) of CouchDB and he told me that I can emit() multiple times within a map. Something I did not know up until now.

To make it easier for myself, I'm assuming your end and start time are TIMESTAMP values already. If not, you need to convert them in your map or generally switch to them.

I'm also gonna assume that an event starts at a full minute (e.g. 16:51:00) and not at 16:51:23. Same on the end date.

Example document:

{
    "_id"   : "super-random-id",
    "name"  : "event 1",
    "start" : "TIMESTAMP",
    "end"   : "TIMESTAMP"
}

Here's the map:

function (doc) {
    if (doc.start == undefined || doc.end == undefined) {
        return;
    }
    var current = doc.start;
    while (current <= doc.end) {
        emit(current, doc.id);
        current = current + 60; // increment by 1 minute
    }
}

Then it should be easy to query with startkey and endkey. You could probably add an _list here.

like image 76
Till Avatar answered Nov 02 '22 23:11

Till