我试图在CouchDB中建立一个相当简单的关系,我无法确定实现这一目标的最佳方法.我希望用户能够创建视频游戏对象列表.我已经将数据库中存储的视频游戏文档包含在内"type":"game".我希望能够查询列表对象的ID(通过视图)并获取列表的元数据(标题,创建日期等)和游戏文档的部分(例如标题和发布日期).此外,我希望能够在列表中添加/删除游戏,而无需下载整个列表文档并将其发回(因此这意味着我不能简单地将游戏信息存储在列表文档中)最终喜欢支持多个用户参与同一个列表,我不想引入冲突.
在EntityRelationships上阅读CouchDB wiki之后,我已经确定设置关系文档可能是最好的解决方案.
{
"_id": "2600emu",
"type": "game"
}
Run Code Online (Sandbox Code Playgroud)
{
"_id": 123,
"title": "Emulators",
"user_id": "dstaley",
"type": "list"
}
Run Code Online (Sandbox Code Playgroud)
{
"_id": "98765456789876543",
"type": "relationship",
"list_id": 123,
"game_id": "2600emu"
}
Run Code Online (Sandbox Code Playgroud)
但是,根据我的理解,这不允许我在一个请求中获取列表的元数据和游戏的元数据.有什么建议?
Mik*_*ler 12
好问题.您确定了一些非常重要的原因,即使用"规范化"数据模型(带链接的不同文档类型)是最佳模型:
你也是对的,这里的解决方案是'map-side-join'(借用hadoop社区).基本上,您希望在地图输出中使用不同的行来表示不同的信息.然后,您可以使用范围查询(startkey/endkey)来查询所需的地图结果部分,并且,瞧,"连接"表的物化视图.但是,您在文档中找不到的一个难题是:
http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views#Linked_documents
第一行:
"如果您发出的对象值为{'_ id':XXX},则include_docs = true将获取ID为XXX的文档,而不是处理为发出键/值对的文档."
这一切都说明了.这就是你取消引用由外键存储的链接文档的指针的方法.然后,将其与使用复合键(JS数组的键)和视图聚合规则相结合:
这样我们的视图行就像:
["list_1"], null
["list_1", "game"], {"_id":"game_1234"}
["list_1", "game"], {"_id":"game_5678"}
["list_2"], null
["list_2","game"], {"_id":"game1234"}
["list_3"], null
...
Run Code Online (Sandbox Code Playgroud)
将此与您现有的数据模型放在一起,这里有一些(未经测试的)伪代码应该可以解决这个问题:
function(doc) {
if (doc.type=="list") {
//this is the one in the one-to-many
emit( [doc._id]),);
}
else if (doc.type=="relationship") {
//this is the many in the one-to-many
//doc.list_id is our foreign key to the list. We use that as the key
//doc.game_id is the foreign key to the game. We use that as the value
emit( [doc.list_id,'game'], {'_id': doc.game_id});
}
}
Run Code Online (Sandbox Code Playgroud)
最后,您将使用startkey/endkey查询,以便获得以您感兴趣的list_id开头的所有行.它看起来像:
curl -g 'https://usr:pwd@usr.cloudant.com/db/_design/design_doc_name/_view/view_name?startkey=["123"]&endkey=["123",{}]&include_docs=true'
Run Code Online (Sandbox Code Playgroud)
该-g选项告诉curl不要为glob,这意味着您不必取消引用方括号等,该include_docs=true选项将跟随指向您game_id在relationship文档中指定的外键的指针.
分析:
| 归档时间: |
|
| 查看次数: |
6157 次 |
| 最近记录: |