将CouchDB javascript视图转换为erlang

Translate CouchDB javascript views to erlang

本文关键字:erlang 转换 视图 CouchDB javascript      更新时间:2023-09-26

我需要一些帮助,将以下CouchDB视图从javascript翻译为erlang。我在erlang中需要它们,因为在javascript中,视图使用所有可用的堆栈内存并崩溃couchjs(参见此bugreport https://issues.apache.org/jira/browse/COUCHDB-893)。

目前我在javascript中的map函数是:

同步/transaction_keys

function(doc) {
  if(doc.doc_type == "Device") {
      for(key in doc.transactions)
          emit(key, null);
  }
}

/同步更新数据

function(doc) {
  if(doc.doc_type == "Device") {
      for(key in doc.transactions) {
          t = doc.transactions[key];
          t.device = doc.device;
          emit(key, t);
     }
  }
}

一个示例文档是:

{
   "_id": "fcef7b5c-cbe6-31af-8363-2b446a7e4cf2",
   "_rev": "3-c90abd075404a75744fd3e5e4f04ebad",
   "device": "fcef7b5c-cbe6-31af-8363-2b446a7e4cf2",
   "doc_type": "Device",
   "transactions": {
       "79fe8630-c0c0-30c6-9913-79b2f93e3e6e": {
           "timestamp": 1309489169533,
           "version": 10008,
           "some_more_data" : "more_data"
       }
       "e4678930-c465-76a6-8821-75a3e888765a": {
           "timestamp": 1309489169533,
           "version": 10008,
           "some_more_data" : "more_data"
       }
   }
}

基本上sync/transaction_keys会发出事务字典中的所有键,而sync/transaction会发出事务字典中的所有条目。

不幸的是,我以前从未使用过Erlang,我需要很快重写这些代码,所以任何帮助都是非常欢迎的。

我刚刚做了你的第二个(更复杂的一个)。从这里可以很容易地推断出第一个:

fun({Doc}) ->
        %% Helper function to get a toplevel value from this doc.
        F = fun(B) -> proplists:get_value(B, Doc) end,
        %% switch on doc type
        case F(<<"doc_type">>) of
            <<"Device">> ->
                %% Grab the transactions from this document
                {Txns} = F(<<"transactions">>),
                lists:foreach(fun({K,V}) ->
                                      %% Emit the key and the value as
                                      %% the transaction + the device
                                      %% id
                                      {T} = proplists:get_value(K, Txns),
                                      Emit(K, {[{<<"device">>, F(<<"device">>)} | T]})
                              end,
                             Txns);
            _ -> false %% Not a device -- ignoring this document
        end
end.