【问题标题】:couchdb views: return all fields in doc as mapcouchdb 视图:将文档中的所有字段作为地图返回
【发布时间】:2020-10-25 15:03:44
【问题描述】:

我在 couchDB 中有一个文档:

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

我想编写一个返回所有这些字段的映射的视图。 地图应如下所示: [{"username","user1"},{"password","password1"},{"server","localhost"}]

这是我想要的伪代码 -

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;
}

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

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

【问题讨论】:

标签: javascript view couchdb couchbase-view


【解决方案1】:

首先你要知道:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多