CouchDB“加入"两个文件 [英] CouchDB "Join" two documents
问题描述
我有两个看起来像这样的文件:
I have two documents that looks a bit like so:
Doc
{
_id: AAA,
creator_id: ...,
data: ...
}
DataKey
{
_id: ...,
credits_left: 500,
times_used: 0,
data_id: AAA
}
我想做的是创建一个视图,该视图允许我传递DataKey id(key = DataKey _id)并同时获取DataKey和文档的信息.
What I want to do is create a view which would allow me to pass the DataKey id (key=DataKey _id) and get both the information of the DataKey and the Doc.
我的尝试
我首先尝试将DataKey嵌入到Doc中,并使用如下所示的map函数:
I first tried embedding the DataKey inside the Doc and used a map function like so:
function (doc)
{
if (doc.type == "Doc")
{
var ids = [];
for (var i in doc.keys)
ids.push(doc.keys[i]._id);
emit(ids, doc);
}
}
但是我遇到两个问题:
- 每个可以有多个DataKey Doc,所以使用startkey = [idhere ...] 并且endkey = [idhere ...,{}]没有 工作(仅在密钥发生时工作 成为数组中的第一个).
- 所有数据密钥都必须是唯一的,我宁愿不要制作像{_id = datakey}这样的单独文档来保留密钥.
- There can be multiple DataKey's per Doc so using startkey=[idhere...] and endkey=[idhere..., {}] didn't work (only worked if the key happend to be the first one in the array).
- All the data keys need to be unique, and I would prefer not making a seperate document like {_id = datakey} to reserve the key.
有人知道我如何做到这一点吗?让我知道是否有任何不清楚的地方.
Does anyone have ideas how I can accomplish this? Let me know if anything is unclear.
-----编辑-----
我忘了提到我的应用程序中我不知道文档ID是什么,因此我需要能够搜索DataKey的ID.
I forgot to mention that in my application I do not know what the Doc ID is, so I need to be able to search on the DataKey's ID.
推荐答案
我认为您想要的是
function (doc)
{
if (doc.type == "Doc")
{
emit([doc._id, 0], doc);
}
if(doc.type == "DataKey")
{
emit([doc.data_id, 1], doc);
}
}
现在,使用key=["AAA"]
查询视图,您将看到所有文档的列表.第一个将是真实的"Doc"文档.其余所有将是引用第一个文档的"DataKey"文档.
Now, query the view with key=["AAA"]
and you will see a list of all docs. The first one will be the real "Doc" document. All the rest will be "DataKey" documents which reference the first doc.
这是一种常见的技术,称为 CouchDB视图排序规则.
This is a common technique, called CouchDB view collation.
这篇关于CouchDB“加入"两个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!