假设:
假设客户数据库中存在以下文档:
[
{
"_id": "93512c6c8585ab360dc7f535ff00bdfa",
"_rev": "1-299289ee89275a8618cd9470733035f4",
"name": "Tom",
"email": "tom@domain.com"
},
{
"_id": "93512c6c8585ab360dc7f535ff00c930",
"_rev": "1-a676883d6f1b5bce3b0a9ece92da6964",
"name": "Tom Doe",
"email": "tom@domain.com"
},
{
"_id": "93512c6c8585ab360dc7f535ff00edc0",
"_rev": "1-09b5bf64cfe66af7e1134448e1a328c3",
"name": "John",
"email": "john@domain.com"
},
{
"_id": "93512c6c8585ab360dc7f535ff010988",
"_rev": "1-88e347af11cfd1e40e63920fa5806fd2",
"name": "Alan",
"email": "alan@domain.com"
}
]
如果我正确理解您的查询,那么根据以上数据,您需要以下给定的结果集。
{
"tom@domain.com": 2,
"alan@domain.com": 1,
"john@domain.com": 1
}
解决方案:
为了实现上述目的,请考虑以下包含具有 Map 和 Reduce 功能的 View 的设计文档。
{
"_id": "_design/Customers",
"views": {
"by-email": {
"map": "function (doc) {
if(doc.email){
emit(doc.email, doc._id);
}
}",
"reduce": "_count"
}
},
"language": "javascript"
}
如果文档中存在键,则上述视图函数发出文档的键email 的值。
reduce 函数 _count 是一个内置的 reducer(由 CouchDB 提供),用于执行计数逻辑。
执行视图查询:
为了查询这个view,你需要:选择视图函数,标记reduce to be executed(因为它是可选的运行reduce)并将1设置为组级别。
您可以通过 UI 执行此操作:
结果:
这是上述查询给出的结果:
[![map reduce查询结果
希望这会有所帮助。
有关其他 reduce 函数和组级别的更多详细信息,请参阅 CouchDB 文档。
干杯。