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.- fun({Doc}) ->
<<K,/binary>> = proplists:get_value(<<"_rev">>, Doc, null),
V = proplists:get_value(<<"_id">>, Doc, null),
Emit(<<K>>, V)
end.
- fun({Doc}) ->
FoldRows
(_Fun, Acc)
Helper to iterate over all rows in a list function.
|Arguments:
|——-
|
- Fun – Function object.
- Acc – The value previously returned by Fun.- 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.
- fun(Head, {Req}) ->
GetRow
()
Retrieves the next row from a related view result.- %% 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.
- %% FoldRows background implementation.
Log
(_Msg)
|Arguments:
|——-
|
- Msg – Log a message at the INFO level.- 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):- [Sun, 04 Nov 2012 11:33:58 GMT] [info] [<0.9144.2>] Hello from 8d300b86622d67953d102165dbe99467 doc!
- fun({Doc}) ->
Send
(_Chunk)
Sends a single string Chunk in response.- fun(Head, {Req}) ->
Send("Hello,"),
Send(" "),
Send("Couch"),
"!"
end.
The function above produces the following response:- Hello, Couch!
- fun(Head, {Req}) ->
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:- fun(Head, {Req}) ->
Start({[{<<"code">>, 302},
{<<"headers">>, {[
{<<"Location">>, <<"http://couchdb.apache.org">>}]
}}
]}),
"Relax!"
end.
- fun(Head, {Req}) ->
原文: http://docs.couchdb.org/en/stable/query-server/erlang.html