Skip to content

Instantly share code, notes, and snippets.

@ratopi
Last active September 9, 2016 19:42
Show Gist options
  • Select an option

  • Save ratopi/9ae38d41ec97ce64f103b307a7bcdf60 to your computer and use it in GitHub Desktop.

Select an option

Save ratopi/9ae38d41ec97ce64f103b307a7bcdf60 to your computer and use it in GitHub Desktop.
Erlang Views in CouchDB

How to activate Erlang-Views in CouchDB

Configuration

local.ini

[native_query_servers]
erlang = {couch_native_process, start_link, []}

Restart

> sudo /etc/init.d/couchdb restart

Map & Reduce

Temporary View

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

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

Filters

Simple

fun({Doc}, {Req}) ->
        DocType = couch_util:get_value(<<"type">>, Doc),
        case DocType of
                undefined -> false;
                <<"mytype">> ->       true;
                _ -> false
        end
end.

With Query-Parameter

fun({Doc}, {Req}) ->
        DocId = couch_util:get_value(<<"_id">>, Doc),
        DocType = couch_util:get_value(<<"type">>, Doc),
        DocValue = couch_util:get_value(<<"value">>, Doc),
        DocDeleted = couch_util:get_value(<<"_deleted">>, Doc),

        {Query} = couch_util:get_value(<<"query">>,Req, {[]}),
        ValuesParam = couch_util:get_value(<<"values">>,Query),
        Values = binary:split(ValuesParam, <<",">>, [global]),
        case {DocId, DocDeleted}  of
        {<<"_design/", _/binary>>, _} -> true;
        {_, true} -> true;
        _ ->
                case DocType of
                        undefined -> false;
                        <<"mytype">> -> lists:any(fun(E) -> E =:= DocValue
end, Values);
                        _ -> false
                end
        end
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment