couchdb视图:以Map形式返回文档中的所有字段

ttisahbt  于 2022-12-09  发布在  CouchDB
关注(0)|答案(1)|浏览(133)

我在couchDB中有一个文档:

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

我想写一个视图,返回所有这些字段的Map。Map应该如下所示:[{“用户名”,“用户1”},{“密码”,“密码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;
}

我不知道如何做我上面评论的部分。请帮助。注意:现在,我想在Map中添加用户名、密码和服务器字段以及它们的值。2但是,我可能会在以后继续添加更多。3我想确保我所做的是可扩展的。
我考虑为每个字段编写一个单独的视图函数。例如:emit(“username”,doc.username)。但这可能不是最好的方法。每次添加新字段时也需要更新。

9rbhqvlz

9rbhqvlz1#

首先,你得知道:
1.在CouchDB中,您将使用键-值对索引视图中的文档。

[
  {"key": "user1", "value": null},
  {"key": "localhost", "value": null}
]

1.每当你编辑一个视图时,它会使索引无效,所以Couch必须重建索引。如果你要向该视图添加新字段,这是你必须考虑的事情。
1.如果要在同一个查询中查询多个字段,则所有这些字段都必须在同一个视图中。如果不是必需的,则可以轻松地为所需的每个字段建立索引。
如果要在同一视图中对多个字段进行索引,可以执行以下操作:

// 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允许进行全文搜索,可能更适合您的需要。

相关问题