Created
July 9, 2011 22:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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