rethinkdb值的频率

时间:2015-12-11 16:53:04

标签: node.js rethinkdb

实施"频率"的方法是什么?在reThinkDB中查询某些值?

示例数据:

[{
 akey : "1",
 anotherkey : "2"
}, {
 akey : "1",
 anotherkey : "2"
}, {
 akey : "AAA",
 anotherkey : "BBB"
}, {
 akey : "CCC",
 anotherkey : "CCC"
}]

应该为akey作为参数:

{
  "1"   : 2,
  "AAA" : 1,
  "CCC" : 1
}

应该为anotherkey作为参数:

{
  "2"   : 2,
  "BBB" : 1,
  "CCC" : 1
}

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

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

没有reduce的另一种方法是:

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')

但是,我喜欢reduce方式,因为它映射到我对整个过程的看法。