我有一個包含一系列事件的couchdb。每個事件都有一個所有者,一個ID,一個它發生的時間和一條消息(加上一堆其他東西,這對本次練習無關緊要)。我想要列出最近發生的事件。我翻看了這個問題CouchDB - filter latest log per logged instance from a list,並嘗試使用它與減速器中的比較翻轉以保留第一條消息(使用具有複雜鍵的表單)。Couchdb map/reduce返回流中的第一個,然後按時間排序
不幸的是,它似乎不太想做什麼。
這是我的地圖功能
function(doc) {
var owner, id;
if (doc.owner
&& doc.stream_id
&& doc.message
&& doc.receipt_time)
{
emit([doc.owner,doc.stream_id,doc.receipt_time],
{ owner: doc.owner,
stream_id: doc.stream_id,
timestamp: doc.receipt_time,
message: doc.message
});
}
}
和我的降低功能
function(keys, values) {
var challenger, winner = null;
for (var a = 0; a < values.length; a++) {
challenger = values[a];
if (! winner) {
winner = challenger;
} else {
if (winner.owner !== challenger.owner
&& winner.trace_id !== challenger.trace_id) {
return null;
} else if (challenger.timestamp < winner.timestamp) {
winner = challenger;
}
}
}
return winner;
}
然後我用?降調用=真&組=真& group_level = 2來得到每個流的第一條消息但是,它似乎不是按時間排序的,而是由owner和stream_id這樣的
{"rows":[
{"key":["sam","a"],
"value":
{"owner":"sam","stream_id":"a","timestamp":1303754236482,"message":"foo"}
},
{"key":["sam","b"],
"value":
{"owner":"sam","stream_id":"b","timestamp":1303752578476,"message":"bar"}
},
{"key":["jim","j1"],
"value":
{"owner":"jim","stream_id":"j1","timestamp":1303625378839,"message":"stuff"}
},
{"key":["bob","loblaw"],
"value":
{"owner":"bob","stream_id":"loblaw","timestamp":1303328396532,"message":"more stuff"}
},
{"key":["anthony","foo"],
"value":
{"owner":"anthony","stream_id":"foo","timestamp":1303769699444,"message":"even more"}
}
]}
(注意,最終條目實際上是最近的時間)。
所以我想要的是最後的觀點是現在它是按時間排序的。有沒有辦法做到這一點?
我想你是誤會。對於任何一個所有者+ stream_id,可以有多達幾千條消息。我想在每個流中顯示第一條消息,然後按時間戳排序。如果你命令它們[owner,stream_id,receipt_time],然後通過group_level 2和我概述的reduce函數,我得到每個流的所有者和stream_id的第一條消息,但是**它們按時間排序。如果我包含receipt_time(即,group_level 3),我會收到每條消息,以便達到目的。 – Nym 2011-04-26 03:52:36
你說得對,我誤解了。我認爲可能還有更簡單的方法可以實現,但我必須考慮這一點。也許其中一位Couch專家會出現並在此期間提供答案。 – 2011-04-26 15:50:37