CouchDB 视图:将文档作为新字段添加到文档
CouchDB View : Add document as a new field to a document
假设我有这两个文件:
{
"type": "ip",
"_id": "321",
"key1": "10",
"key2": "20",
"ip_config": {
"ip": "127.0.0.1",
"connexion": "WIFI"
}
}
{
"type": "device",
"_id": "1",
"key1": "10",
"key2": "20",
"device": {
"port": "8808",
"bits": 46
}
}
我想在 CouuchDB 中生成一个视图,为我提供以下输出:
{
"key1": "10",
"key2": "20",
"ip_config": {
"port": "8808",
"bits": 46
},
"device": {
"port": "8808",
"bits": 46
}
}
可以帮助我获得此输出的地图函数是什么?
正如 @RamblinRose 所指出的,您不能将文档“加入”视图。您唯一可以做的就是发出文档之间通用的键(在这种情况下,看起来 key1
和 key2
标识了这种关系)。
因此,如果您有一个名为 devices
的数据库,并创建了一个名为 test
的设计文档,其中包含一个名为 device-view 的视图和映射函数:
function (doc) {
emit([doc.key1, doc.key2], null);
}
那么你就可以得到key1和key2组合相关的所有文档:
https:///host/devices/_design/test/_view/device-view?include_docs=true&key=[%2210%22,%2220%22]
这会给你:
{"total_rows":2,"offset":0,"rows":[
{"id":"1","key":["10","20"],"value":null,"doc":{"_id":"1","_rev":"1-630408a91350426758c0932ea109f4d5","type":"device","key1":"10","key2":"20","device":{"port":"8808","bits":46}}},
{"id":"321","key":["10","20"],"value":null,"doc":{"_id":"321","_rev":"1-09d9a676c37f17c04a2475492995fade","type":"ip","key1":"10","key2":"20","ip_config":{"ip":"127.0.0.1","connexion":"WIFI"}}}
]}
这不会执行联接,因此您必须处理它们才能获得单个文档。
假设我有这两个文件:
{
"type": "ip",
"_id": "321",
"key1": "10",
"key2": "20",
"ip_config": {
"ip": "127.0.0.1",
"connexion": "WIFI"
}
}
{
"type": "device",
"_id": "1",
"key1": "10",
"key2": "20",
"device": {
"port": "8808",
"bits": 46
}
}
我想在 CouuchDB 中生成一个视图,为我提供以下输出:
{
"key1": "10",
"key2": "20",
"ip_config": {
"port": "8808",
"bits": 46
},
"device": {
"port": "8808",
"bits": 46
}
}
可以帮助我获得此输出的地图函数是什么?
正如 @RamblinRose 所指出的,您不能将文档“加入”视图。您唯一可以做的就是发出文档之间通用的键(在这种情况下,看起来 key1
和 key2
标识了这种关系)。
因此,如果您有一个名为 devices
的数据库,并创建了一个名为 test
的设计文档,其中包含一个名为 device-view 的视图和映射函数:
function (doc) {
emit([doc.key1, doc.key2], null);
}
那么你就可以得到key1和key2组合相关的所有文档:
https:///host/devices/_design/test/_view/device-view?include_docs=true&key=[%2210%22,%2220%22]
这会给你:
{"total_rows":2,"offset":0,"rows":[
{"id":"1","key":["10","20"],"value":null,"doc":{"_id":"1","_rev":"1-630408a91350426758c0932ea109f4d5","type":"device","key1":"10","key2":"20","device":{"port":"8808","bits":46}}},
{"id":"321","key":["10","20"],"value":null,"doc":{"_id":"321","_rev":"1-09d9a676c37f17c04a2475492995fade","type":"ip","key1":"10","key2":"20","ip_config":{"ip":"127.0.0.1","connexion":"WIFI"}}}
]}
这不会执行联接,因此您必须处理它们才能获得单个文档。