cloudant groupby 和 count 值出现的次数
cloudant groupby and count number of times a value appears
第一次使用没有sql 的数据库,在编写查询时遇到了问题,该查询可以在我的数据库中查找,并且对于一个键,可以计算另一个键出现的次数。
例如,如果我的数据库包含
{
"person": "user1",
"status": "good"
},
{
"person": "user1",
"status": "good"
},
{
"person": "user1",
"status": "bad"
},
{
"person": "user2",
"status": "good"
}
想知道 person1 好 2 和坏 1 而 person2 只有好 1
在 sql 会做
select person, status, count(*)
from mydb
groupby person, status
或者由数据库中的用户获取它
select person, status, count(*)
from mydb
groupby person, status
where person = "user1"
You can achieve this with Cloudant's MapReduce views and suitably chosen query parameters.我创建了一个地图所在的视图
function (doc) {
emit([doc.person, doc.status], null);
}
和减少内置 _count
。这给了我们一个索引,其中键是一个向量,然后我们可以在不同的级别进行分组。使用 groupby=true
和 group_level=2
给我们想要的结果:
curl 'https://A.cloudant.com/D/_design/so/_view/by-status?groupby=true&group_level=2'
{
"rows": [
{
"key": [
"user1",
"bad"
],
"value": 1
},
{
"key": [
"user1",
"good"
],
"value": 2
},
{
"key": [
"user2",
"good"
],
"value": 1
}
]
}
第一次使用没有sql 的数据库,在编写查询时遇到了问题,该查询可以在我的数据库中查找,并且对于一个键,可以计算另一个键出现的次数。
例如,如果我的数据库包含
{
"person": "user1",
"status": "good"
},
{
"person": "user1",
"status": "good"
},
{
"person": "user1",
"status": "bad"
},
{
"person": "user2",
"status": "good"
}
想知道 person1 好 2 和坏 1 而 person2 只有好 1 在 sql 会做
select person, status, count(*)
from mydb
groupby person, status
或者由数据库中的用户获取它
select person, status, count(*)
from mydb
groupby person, status
where person = "user1"
You can achieve this with Cloudant's MapReduce views and suitably chosen query parameters.我创建了一个地图所在的视图
function (doc) {
emit([doc.person, doc.status], null);
}
和减少内置 _count
。这给了我们一个索引,其中键是一个向量,然后我们可以在不同的级别进行分组。使用 groupby=true
和 group_level=2
给我们想要的结果:
curl 'https://A.cloudant.com/D/_design/so/_view/by-status?groupby=true&group_level=2'
{
"rows": [
{
"key": [
"user1",
"bad"
],
"value": 1
},
{
"key": [
"user1",
"good"
],
"value": 2
},
{
"key": [
"user2",
"good"
],
"value": 1
}
]
}