3.3. Erlang

Emit(Id, Value)

Emits key-value pairs to view indexer process.

  1. fun({Doc}) ->
  2. <<K,_/binary>> = proplists:get_value(<<"_rev">>, Doc, null),
  3. V = proplists:get_value(<<"_id">>, Doc, null),
  4. Emit(<<K>>, V)
  5. 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}) ->
  2. Fun = fun({Row}, Acc) ->
  3. Id = couch_util:get_value(<<"id">>, Row),
  4. Send(list_to_binary(io_lib:format("Previous doc id: ~p~n", [Acc]))),
  5. Send(list_to_binary(io_lib:format("Current doc id: ~p~n", [Id]))),
  6. {ok, Id}
  7. end,
  8. FoldRows(Fun, nil),
  9. ""
  10. end.

GetRow()

Retrieves the next row from a related view result.

  1. %% FoldRows background implementation.
  2. %% https://git-wip-us.apache.org/repos/asf?p=couchdb.git;a=blob;f=src/couchdb/couch_native_process.erl;hb=HEAD#l368
  3. %%
  4. foldrows(GetRow, ProcRow, Acc) ->
  5. case GetRow() of
  6. nil ->
  7. {ok, Acc};
  8. Row ->
  9. case (catch ProcRow(Row, Acc)) of
  10. {ok, Acc2} ->
  11. foldrows(GetRow, ProcRow, Acc2);
  12. {stop, Acc2} ->
  13. {ok, Acc2}
  14. end
  15. end.

Log(Msg)

Arguments:
  • Msg – Log a message at the INFO level.
  1. fun({Doc}) ->
  2. <<K,_/binary>> = proplists:get_value(<<"_rev">>, Doc, null),
  3. V = proplists:get_value(<<"_id">>, Doc, null),
  4. Log(lists:flatten(io_lib:format("Hello from ~s doc!", [V]))),
  5. Emit(<<K>>, V)
  6. end.

After the map function has run, the following line can be found in CouchDB 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}) ->
  2. Send("Hello,"),
  3. Send(" "),
  4. Send("Couch"),
  5. "!"
  6. end.

The function above produces the following response:

  1. Hello, Couch!

Start(Headers)

Arguments:

Initialize List Functions response. At this point, response code and headers may be defined. For example, this function redirects to the CouchDB web site:

  1. fun(Head, {Req}) ->
  2. Start({[{<<"code">>, 302},
  3. {<<"headers">>, {[
  4. {<<"Location">>, <<"http://couchdb.apache.org">>}]
  5. }}
  6. ]}),
  7. "Relax!"
  8. end.