【问题标题】:Erlang - Conditionally Omit A Property From A Couch DB ViewErlang - 有条件地忽略 Couch DB 视图中的属性
【发布时间】:2015-02-10 06:01:10
【问题描述】:

我有一个 Erlang Couch DB,它呈现一个 JSON 对象,如下所示:

fun({Doc}) ->
    Name = couch_util:get_value(<<\"name\">>, Doc),
    Value = couch_util:get_value(<<\"Value\">>, Doc),
    Geocode = couch_util:get_value(<<\"geocode\">>, Doc),
    Emit(
        Name,
        {[
            { <<\"value\">>,Value }, 
            { <<\"geocode\">>, Geocode }            
        ]}
    )
end.

问题在于此视图中的所有文档都没有“地理编码”属性。在不存在地理编码的情况下,我宁愿不显示它。在伪代码中,我基本上想这样做......

Emit(
    Name,
    {[
        { <<\"value\">>,Value }, 
        Geocode != undefined ? { <<\"geocode\">>, Geocode } : null  
    ]}
);

我怀疑在 Erlang 中做到这一点不会那么容易?

到目前为止,我最好的解决方案是:

fun({Doc}) ->
    Name = couch_util:get_value(<<\"name\">>, Doc),
    Value = couch_util:get_value(<<\"Value\">>, Doc),
    Geocode = couch_util:get_value(<<\"geocode\">>, Doc),
    % I think 'couch_util:get_value' returns the atom undefined, if the value doesn't exist.
    Undefined = undefined,
    if Geocode /= Undefined ->
        Emit(
            Name,
            {[
                { <<\"value\">>, Value }, 
                { <<\"geocode\">>, Geocode }            
            ]}
        );
    true -> Emit(Name, {[ { <<\"value\">>, Value } ]})
    end;
end.

很确定那里会有一两个语法错误...请随时指出它们! 但更重要的是,有没有更有效的方法来有条件地从 proplist / 视图中删除 'geocode' 值?

【问题讨论】:

    标签: syntax mapreduce erlang couchdb conditional


    【解决方案1】:

    您要做的是过滤掉缺失的属性。

    让我们用list comprehension生成proplist:

    ListOfKeys = [<<"value">>, <<"geocode">>], Proplist = [{Key, couch_util:get_value(Key, Doc)} || Key <- ListOfKeys],

    让我们 filter/2 输出带有 undefined 值的道具:

    FilteredProplist = lists:filter( fun ({_Key, undefined}) -> false; % it matches => it's out ({_Key, _Value}) -> true end, Proplist),

    现在你可以Emit(Name, FilteredProplist)

    也可以在列表理解中过滤掉它们,但看起来不太清楚:

    FilteredProplist = [{Key, Value} || Key <- ListOfKeys, Value <- [couch_util:get_value(Key, Doc)], Value /= undefined]

    编辑: 哦...我想我错过了最重要的问题:如何用 erlang 编写它?

    {[ { <<\"value\">>,Value }, Geocode != undefined ? { <<\"geocode\">>, Geocode } : null ]}

    答案是:

    { [{ <<"value">>,Value }] ++ if Geocode /= undefined -> [{ <<"geocode">>, Geocode }]; true -> [] end }

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多