couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From kowsik <kow...@gmail.com>
Subject Note to self...
Date Fri, 17 Oct 2008 19:12:21 GMT
This might be obvious to most of you, but wasn't for me. Just thought
I'll share. I have a bunch of design views that come in pairs:
count_of_blah and values_for_blah where the only difference is as
follows:

count_of_blah:
    map => emit(doc.key, 1);
    reduce => return sum(values);

values_for_blah:
    map => emit(doc.key, doc.value);
    reduce => return values;

There was just a little too much repetition in the code (not to
mention the extra pass over the documents to generate the indices)
since for the most part the differences were in the emit and reduce
functions. Well, until I figured out that the reduce function gets
invoked with __all__ of the keys and values, which means I can build
both types of indexes in one go like so:

map => function(doc) {
    emit([ "count", doc.key ], doc.value);
    emit([ "list", doc.key ], doc.value);
}

reduce => function(keys, values) {
    if (keys) {
        var element = keys[0]; // keys is an array of __all__ emit's
that share the same key (but different doc._id)
        var emit_key = element[0]; // each element is an array of the
actual emitted key + the doc._id
        if (emit_key[0] == "count") {
            return values.length;
        }
    }
    return values;
}

Now to get the count of some "foo", I just have to invoke:

    /_view/blah/count_of_blah?group=true&key=["count","foo"]

And to get all the values for 'foo':

    /_view/blah/count_of_blah?group=true&key=["list","foo"]

Anyways, saved myself from a lot of repetition and I now have half the
number of design docs, which hopefully also means that the indexing
takes lesser time.

Is there an alternate, better of doing this?

K.

Mime
View raw message