我是CouchDB的新手并且正在努力实现一个基本的例子。我有三个文件客户,联系人,地址,我想将他们加入一个文件。
帐户文件
{
"_id": "CST-1",
"_rev": "8-089da95f148b446bd3b33a3182de709f",
"name": "Customer",
"code": "CST-001",
"contact_Key": "CNT-001",
"address_Key": "ADD-001",
"type": "Customer"
}
联系文件
{
"_id": "CNT-001",
"_rev": "8-079da95f148b446bd3b33a3182de709g",
"fullname": "Happy Swan",
"type": "Contact"
}
地址文件
{
"_id": "ADD-001",
"_rev": "8-179da95f148b446bd3b33a3182de709c",
"street1": "9 Glass View",
"street2": "Street 2",
"city": "USA",
"type": "Address"
}
地图/查询:
var map= function (doc) {
if (doc.type === 'Customer') {
emit(doc.id, { contact_Key: doc.contact_Key, address_Key: doc.address_Key })
}
};
db.query({ map: map }, { include_docs: true }, function (err, res) {
});
我在查询帐户时希望将所有3个文档放在一个文档中。
预期结果
{
"_id": "CST-1",
"_rev": "8-089da95f148b446bd3b33a3182de709f",
"name": "Customer",
"code": "CST-001",
"contact_Key": "CNT-001",
"address_Key": "ADD-001",
"type": "Customer",
"Contact: {
"_id": "CNT-001",
"_rev": "8-079da95f148b446bd3b33a3182de709g",
"fullname": "Happy Swan",
"type": "Contact"
}",
"Address: {
"_id": "ADD-001",
"_rev": "8-179da95f148b446bd3b33a3182de709c",
"street1": "9 Glass View",
"street2": "Street 2",
"city": "USA",
"type": "Address"
}"
}
答案 0 :(得分:0)
我没有看到比先查询帐户文档更好的解决方案,然后在知道其ID后再查询其他两个。如果您考虑一下,这是有道理的,因为这些文档之间的唯一链接是存储在帐户文档中的ID,因此要在同一时间获取所有三个,在内部数据库必须执行两个查询:首先是帐户文档,然后另外两个。而按设计,CouchDB一次只能进行一次查询。
如果您将帐户文档ID存储在联系人和地址文档中,则可以使用list function将它们合并为一个。
首先你需要一个观点:
function(doc) {
if (doc.type === 'Customer') {
emit(doc._id, doc);
}
if (doc.type === 'Contact' || doc.type === 'Address') {
emit(doc.account_id, doc);
}
}
然后是列表功能:
function(head, req) {
var row, account, contact, address;
while (row = getRow()) {
if (row.value.type === 'Customer') {
account = row.value;
} else if (row.value.type === 'Contact') {
contact = row.value;
} else if (row.value.type === 'Address') {
address = row.value;
}
}
account['Contact'] = contact;
account['Address'] = address;
provides("json", function() {
return { 'json': account };
});
}
你可以用以下方式查询:
GET /db/_design/foo/_list/the-list/the-view?key="CST-1"