Skip to content

Instantly share code, notes, and snippets.

@KlausTrainer
Created July 9, 2011 22:12
Show Gist options
  • Save KlausTrainer/1073999 to your computer and use it in GitHub Desktop.
Save KlausTrainer/1073999 to your computer and use it in GitHub Desktop.
A native list function for CouchDB that groups view results by its first key element.
fun(Head, {Req}) ->
Fun = fun({Row}, {PrevKey, RowCount}) ->
Key = case couch_util:get_value(<<"key">>, Row) of
K when is_list(K) -> hd(K);
K -> K
end,
Doc = couch_util:get_value(<<"value">>, Row),
DocJson = couch_util:to_binary(couch_util:json_encode(Doc)),
KeyJson = <<"{\"key\":\"",Key/binary,"\"">>,
ValueJson = <<"\"value\":[",DocJson/binary>>,
case Key of
PrevKey ->
Send(<<",",DocJson/binary>>);
_ ->
case RowCount of
0 ->
Send(<<"{\"rows\":[",KeyJson/binary,",",ValueJson/binary>>);
_ ->
Send(<<"]},",KeyJson/binary,",",ValueJson/binary>>)
end
end,
{ok, {Key, RowCount + 1}}
end,
FoldRows(Fun, {nil, 0}),
Send(<<"]}]}">>)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment