# 7.3. Erlang

Note

The Erlang query server is disabled by default. Read configuration guide about reasons 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.

`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 = couch_util: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.

      %% 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.

      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 in CouchDB 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!

`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!

`Start`(Headers)

  Arguments: | Headers – Proplist of response object.

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

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