我有一个用Erlang编写的CouchDB列表,如下面的代码所示。此列表将输出每行的计数。我需要的是在遍历所有行之后“发送”计数。 (仅获得最终计数)。
我怎样才能完成这项工作?尝试使用ets但无法成功。
fun(Head, {Req}) ->
Fun = fun({Row}, Acc) ->
TheType = proplists:get_value(<<"type">>, element(1,proplists:get_value(<<"value">>,Row))),
case TheType of
<<"TYPEONE">> ->
Count = Acc+1;
_ ->
Count = Acc
end,
Send(list_to_binary(io_lib:format("Count: ~p~n", [Count]))),
{ok, Count}
end,
FoldRows(Fun, 0),
""
end.
答案 0 :(得分:1)
以下功能对我有用: -
fun(Head, {Req}) ->
Fun = fun({Row}, Acc) ->
{Val} = couch_util:get_value(<<"value">>, Row, rest),
TheType = proplists:get_value(<<"TheType">>, Val),
case TheType of
<<"TYPEONE">> ->
{ok,Acc+1};
_->
{ok,Acc}
end
end,
{ok, Count} = FoldRows(Fun, 0),
Send(list_to_binary(integer_to_list(Count)))
end.
它检查TheType
是否为&lt;&lt;&#34; TYPEONE&#34;&gt;&gt;如果是,则返回递增的Acc
。处理完所有行后,最终结果为Send
。由于您没有提供任何文件,我认为文档具有以下结构: -
{
"_id": "1fa48be41889b04936c0bf0b570002a2",
"_rev": "1-29eb2f161688277924b6a4a4e7ad7a78",
"TheType": "TYPEONE"
}
并且列表的视图功能如下: -
fun({Doc}) ->
K = proplists:get_value(<<"TheType">>, Doc, null),
Emit(K, {Doc})
end.
答案 1 :(得分:0)
尽管如此,我可以给你一些线索
定义一个过滤函数,如果该行符合您的条件则返回1,否则为0:
Filter = fun({Row},Type) ->
case proplists:get_value(<<"type">>, element(1,proplists:get_value(<<"value">>,Row))) of
Type -> 1;
_ -> 0
end
end,
然后你需要一个你所有行的列表,你的代码示例中缺少这些列表,假设RowList是一个包含{Row}形式元素的列表。
现在您可以使用列表库来创建Count函数:
Count = fun(RowList,Type) -> lists:foldl(fun(X,Acc) -> Filter(X,Type) + Acc end, 0, RowList) end,
并像Count(RowList,<<"TYPEONE">>)
如shell中所示:
27> E1 = {[{foo,0},{<<"value">>,{[{bar,0},{<<"type">>,<<"TYPEONE">>}],baz}}]}.
{[{foo,0},
{<<"value">>,{[{bar,0},{<<"type">>,<<"TYPEONE">>}],baz}}]}
28> E2 = {[{foo,0},{<<"value">>,{[{bar,0},{<<"type">>,<<"TYPETWO">>}],baz}}]}.
{[{foo,0},
{<<"value">>,{[{bar,0},{<<"type">>,<<"TYPETWO">>}],baz}}]}
29> E3 = {[{foo,0},{<<"value">>,{[{bar,0},{<<"notype">>,<<"TYPEONE">>}],baz}}]}.
{[{foo,0},
{<<"value">>,{[{bar,0},{<<"notype">>,<<"TYPEONE">>}],baz}}]}
30> E4 = {[{foo,0},{<<"value">>,{[{bar,0},{<<"type">>,<<"TYPEONE">>}],baz}}]}.
{[{foo,0},
{<<"value">>,{[{bar,0},{<<"type">>,<<"TYPEONE">>}],baz}}]}
31> RowList = [E1,E2,E3,E4].
[{[{foo,0},
{<<"value">>,{[{bar,0},{<<"type">>,<<"TYPEONE">>}],baz}}]},
{[{foo,0},
{<<"value">>,{[{bar,0},{<<"type">>,<<"TYPETWO">>}],baz}}]},
{[{foo,0},
{<<"value">>,{[{bar,0},{<<"notype">>,<<"TYPEONE">>}],baz}}]},
{[{foo,0},
{<<"value">>,{[{bar,0},{<<"type">>,<<"TYPEONE">>}],baz}}]}]
32> Count(RowList,<<"TYPEONE">>).
2
33> Count(RowList,<<"TYPETWO">>).
1
34>