查询Couchbase DB在哪里

时间:2016-10-24 12:08:16

标签: couchdb couchbase

我需要在以下条件下查询CouchDB数据库。 我有像

这样的员工实体的文档
{
  "first Name" : "ABC",
   "role" : "developer",
   "department" : [
                    {
                      "name" : "HR",
                      "country" : "Germany"
                    },
                    {
                      "name" : "Finance",
                      "country" : "USA"
                    },
                    {
                      "name" : "HR",
                      "country" : "USA"
                    }
                  ]

}

如何获取部门所在的文件" HR"在COuchbase?

1 个答案:

答案 0 :(得分:2)

使用CouchBase,您可以使用视图或索引。我给你一个"地图视图"溶液

地图功能如下所示:

function(doc) {
    if (doc.type === "employee") {
        if (doc.department && doc.department.length) {

            for (var i = 0; i < doc.department.length; i++) {
                emit(doc.department[i].name);
            }
        }
    }
}

注意此地图为我们提供类型&#34;员工&#34;。强烈建议将您的文档分组,就好像它们在哪里?#34; table&#34;通过将它们与密钥相关联。例如,每个员工文档可以是&#34; employee&#34;类型。此外,此map函数将两次发出相同的键。您可以轻松地将JavaScript更改为仅发出唯一值,或者您可以使用reduce函数。

要查询视图,您可以执行以下操作:

GET http://localhost:5984/dbname/_design/yourDesignName/_view/byDept?include_docs=true

<强>输出

{
    totalRows: 3,
    rows: [{
        "id": "ABCEmployee",
        "key": "HR",
        "value": null,
        "doc": {
            "first Name": "ABC",
            "role": "developer",
            "department": [{
                "name": "HR",
                "country": "Germany"
            }, {
                "name": "Finance",
                "country": "USA"
            }, {
                "name": "HR",
                "country": "USA"
            }]

        }
    },
    {
        "id": "ABCEmployee",
        "key": "Finance",
        "value": null,
        "doc": {
            "first Name": "ABC",
            "role": "developer",
            "department": [{
                "name": "HR",
                "country": "Germany"
            }, {
                "name": "Finance",
                "country": "USA"
            }, {
                "name": "HR",
                "country": "USA"
            }]

        }
    },
    {
        "id": "ABCEmployee",
        "key": "HR",
        "value": null,
        "doc": {
            "first Name": "ABC",
            "role": "developer",
            "department": [{
                "name": "HR",
                "country": "Germany"
            }, {
                "name": "Finance",
                "country": "USA"
            }, {
                "name": "HR",
                "country": "USA"
            }]

        }
    },
    ]

}

如果您想查询,请说出具有部门&#34; HR&#34;的每个文档,请执行以下操作: GET http://localhost:5984/dbname/_design/yourDesignName/_view/byDept?include_docs=true&key="HR"