Reputation: 18005
What is the way to implement a "frequency" query in reThinkDB for some value ?
Example data :
[{
akey : "1",
anotherkey : "2"
}, {
akey : "1",
anotherkey : "2"
}, {
akey : "AAA",
anotherkey : "BBB"
}, {
akey : "CCC",
anotherkey : "CCC"
}]
Should yield for akey
as parameter :
{
"1" : 2,
"AAA" : 1,
"CCC" : 1
}
Should yield for anotherkey
as parameter :
{
"2" : 2,
"BBB" : 1,
"CCC" : 1
}
Upvotes: 1
Views: 50
Reputation: 2314
You can try something like this:
r.expr([{
akey : "1",
anotherkey : "2"
}, {
akey : "1",
anotherkey : "2"
}, {
akey : "AAA",
anotherkey : "BBB"
}, {
akey : "CCC",
anotherkey : "CCC"
}]).map(function(doc) {
return r.branch(doc.keys().contains('akey'),{'value': doc('akey')},{})
})
.group('value')
.count()
.ungroup()
.map(function(doc) {
return r.object(doc('group'), doc('reduction'))
})
.reduce(function(left, right) {
return left.merge(right)
})
Another way to do it without reduce
is:
r.expr([{
akey : "1",
anotherkey : "2"
}, {
akey : "1",
anotherkey : "2"
}, {
akey : "AAA",
anotherkey : "BBB"
}, {
akey : "CCC",
anotherkey : "CCC"
}]).map(function(doc) {
return r.branch(doc.keys().contains('anotherkey'),{'value': doc('anotherkey')},{})
})
.group('value')
.count()
.ungroup()
.map(function(doc) {
return [doc('group'), doc('reduction')]
})
.coerceTo('object')
However, I like reduce
way because it maps to how I think about the whole process.
Upvotes: 1