8.3. Erlang

Note

The Erlang query server is disabled by default.Read configuration guide aboutreasons why and how to enable it.

Emit(Id, Value)

Emits key-value pairs to view indexer process.




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



FoldRows(_Fun, Acc)

Helper to iterate over all rows in a list function.

|Arguments:
|——-
|
- Fun – Function object.
- Acc – The value previously returned by Fun.





  1. fun(Head, {Req}) ->
    Fun = fun({Row}, Acc) ->
    Id = couchutil:get_value(<<"id">>, Row),
    Send(list_to_binary(io_lib:format("Previous doc id: ~p~n", [Acc]))),
    Send(list_to_binary(io_lib:format("Current doc id: ~p~n", [Id]))),
    {ok, Id}
    end,
    FoldRows(Fun, nil),
    ""
    end.



GetRow()

Retrieves the next row from a related view result.




  1. %% FoldRows background implementation.
    %% https://git-wip-us.apache.org/repos/asf?p=couchdb.git;a=blob;f=src/couchdb/couch_native_process.erl;hb=HEAD#l368
    %%
    foldrows(GetRow, ProcRow, Acc) ->
    case GetRow() of
    nil ->
    {ok, Acc};
    Row ->
    case (catch ProcRow(Row, Acc)) of
    {ok, Acc2} ->
    foldrows(GetRow, ProcRow, Acc2);
    {stop, Acc2} ->
    {ok, Acc2}
    end
    end.



Log(_Msg)

|Arguments:
|——-
|
- Msg – Log a message at the INFO level.





  1. fun({Doc}) ->
    <<K,/binary>> = proplists:get_value(<<"_rev">>, Doc, null),
    V = proplists:get_value(<<"_id">>, Doc, null),
    Log(lists:flatten(io_lib:format("Hello from ~s doc!", [V]))),
    Emit(<<K>>, V)
    end.




After the map function has run, the following line can be found inCouchDB logs (e.g. at
/var/log/couchdb/couch.log):




  1. [Sun, 04 Nov 2012 11:33:58 GMT] [info] [<0.9144.2>] Hello from 8d300b86622d67953d102165dbe99467 doc!



Send(_Chunk)

Sends a single string Chunk in response.




  1. fun(Head, {Req}) ->
    Send("Hello,"),
    Send(" "),
    Send("Couch"),
    "!"
    end.




The function above produces the following response:




  1. Hello, Couch!



Start(Headers)

|Arguments:
|——-
|
- Headers – Proplist of response object.


Initialize List Functions response. At this point, response code and headersmay be defined. For example, this function redirects to the CouchDBweb site:




  1. fun(Head, {Req}) ->
    Start({[{<<"code">>, 302},
    {<<"headers">>, {[
    {<<"Location">>, <<"http://couchdb.apache.org&#34;>>}]
    }}
    ]}),
    "Relax!"
    end.



原文: http://docs.couchdb.org/en/stable/query-server/erlang.html