CouchDB 视图:将 DOC 中的所有字段作为 map 返回



我在couchDB中有一个文档:

{
"id":"avc",
"type":"Property",
"username":"user1",
"password":"password1",
"server":"localhost"
}

我想编写一个返回所有这些字段映射的视图。 映射应如下所示:[{"用户名","user1"},{"密码","密码1"},{"服务器","本地主机"}]

这是我想要的伪代码——

HashMap<String,String> getProperties()
{
HashMap<String,String> propMap;
if (doc.type == 'Property')
{
//read all fields in doc one by one
//get value and add field/value to the map
}
return propMap;
}

我不确定如何做我上面评论的部分。请帮忙。 注意:现在,我想在映射中添加用户名,密码和服务器字段及其值。但是,我以后可能会继续添加更多内容。我想确保我所做的是可扩展的。

我考虑为每个字段编写一个单独的视图函数。例如:emit("用户名",doc.username(。 但这可能不是最好的方法。每次添加新字段时也需要更新。

首先,你必须知道:

  1. 在 CouchDB 中,您将使用键值对为视图中的文档编制索引。因此,如果索引属性用户名和服务器,则将具有以下视图:
[
{"key": "user1", "value": null},
{"key": "localhost", "value": null}
]
  1. 每当您编辑视图时,它都会使索引失效,因此 Couch 必须重建索引。如果要向该视图添加新字段,则必须考虑这一点。
  2. 如果要在同一查询中查询多个字段,则所有这些字段必须位于同一视图中。如果这不是必需的,那么您可以轻松地为所需的每个字段构建索引。

如果要在同一视图中为多个字段编制索引,可以执行以下操作:

// We define a map function as a function which take a single parameter: The document to index.
(doc) => {
// We iterate over a list of fields to index
["username", "password", "server"].forEach((key, value) => {
// If the document has the field to index, we index it.
if (doc.hasOwnProperty(key)) {
// map(key,value) is the function you call to index your document.
// You don't need to pass a value as you'll be able to get the macthing document by using include_docs=true
map(doc[key], null);
}
});
};

另外,请注意,Apache Lucene允许进行全文搜索,并且可能更适合您的需求。

最新更新