我對couchDB非常新,甚至在閱讀"how to store hierarchical data"後,它仍然沒有點擊。從CouchDB檢索分層/嵌套數據
而不是使用維基中描述的完整路徑模式我希望跟蹤孩子作爲一個UUID數組和父母作爲單個UUID。我傾向於這種模式,所以我可以通過他們在兒童陣列中的位置來維護兒童的順序。
以下是沙發上的一些示例文檔,水桶可以包含水桶和物品,物品只能包含其他物品。 (UUIDs爲了清晰起見而縮寫):
{_id: 3944
name: "top level bucket with two items"
type: "bucket",
parent: null
children: [8989, 4839]
}
{_id: 8989
name: "second level item with no sub items"
type: "item"
parent: 3944
}
{
_id: 4839
name: "second level bucket with one item"
type: "bucket",
parent: 3944
children: [5694]
}
{
_id: 5694
name: "third level item (has one sub item)"
type: "item",
parent: 4839,
children: [5390]
}
{
_id: 5390
name: "fourth level item"
type: "item"
parent: 5694
}
是否有可能通過嵌入文檔ID在地圖功能中查找文檔?
function(doc) {
if(doc.type == "bucket" || doc.type == "item")
emit(doc, null); // still working on my key value output structure
if(doc.children) {
for(var i in doc.children) {
// can i look up a document here using ids from the children array?
doc.children[i]; // psuedo code
emit(); // the retrieved document would be emitted here
}
}
}
}
在理想世界中,最終的JSON輸出看起來像這樣。
{"_id":3944,
"name":"top level bucket with two items",
"type":"bucket",
"parent":"",
"children":[
{"_id":8989, "name":"second level item with no sub items", "type":"item", "parent":3944},
{"_id": 4839, "name":"second level bucket with one item", "type":"bucket", "parent":3944, "children":[
{"_id":5694", "name":"third level item (has one sub item)", "type":"item", "parent": 4839, "children":[
{"_id":5390, "name":"fourth level item", "type":"item", "parent":5694}
]}
]}
]
}
感謝您幫助Marcello。當我運行map函數時,輸出並不像我希望的那樣嵌套,而是完全平坦。有任何想法嗎? – berg 2011-05-26 08:01:56
我的答案是[here](http://stackoverflow.com/questions/6084741/how-to-merge-view-collation-into-useful-output-in-couchdb/6094540#6094540)。但我不推薦它。嵌套列表的優點是什麼?扁平列表的排列順序是讓每個「項目」或「桶」緊隨其子代的請求順序。遍歷此列表非常簡單且高效。爲什麼你需要一個嵌套列表?可能是我可以給你一個更好的解決方案。 – 2011-05-26 15:12:31
我希望直接在我的客戶端JavaScript代碼中使用結果,這些代碼期望數據返回嵌套。但是在閱讀了與之相關的問題之後,看起來這與CouchDB的問題背道而馳,所以我打算做這個客戶端!再次感謝我將此標記爲答案! – berg 2011-05-26 17:39:02