Erlang Map/Reduce in CouchDB

Thursday, 15 October 2009

After some initial confusion on my part, it appears that a native Erlang view server has made the 0.10.0 release of CouchDB. Unfortunately, at the time of writing, there is no documentation on enabling or using this feature. The only example currently available is in the test suite, so for anyone else wanting to play around with Erlang map/reduce functions, these are the steps I carried out on Ubuntu Jaunty…

First, you'll need to edit your local.ini to include a native query servers section:

erlang = {couch_native_process, start_link, []}

Your local.ini will most likely be at /usr/local/etc/couchdb/local.ini or /etc/couchdb/local.ini. To see these changes you will also need to restart the server:

sudo /etc/init.d/couchdb restart

To test out using Erlang views, visit the Futon admin interface, create a new database and open a temporary view. You should now be able to select erlang from the language drop-down. Let's try an example of map/reduce functions which count the total documents at each number of revisions (there are x many documents at version "1", and y documents at "2"… etc). Add a few documents to the database, then enter the following functions as a temporary view:

%% Map Function
fun({Doc}) ->
    <<K,_/binary>> = proplists:get_value(<<"_rev">>, Doc, null),
    V = proplists:get_value(<<"_id">>, Doc, null),
    Emit(<<K>>, V)

%% Reduce Function
fun(Keys, Values, ReReduce) -> length(Values) end.

If all has gone well, you should see a list of the total number of documents at each revision number. Have fun!

Edit: I've now added this to the CouchDB wiki.