【问题标题】:rethinkdb frequency of values重新思考值的频率
【发布时间】:2015-12-11 16:53:04
【问题描述】:

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

【问题讨论】:

  • 文档中是否有一个看起来像示例数据的数组,或者每个 { akey : "1", anotherkey : "2"} 是否代表一个单独的文档?
  • @Tholle 这些是单独的文件。

标签: node.js rethinkdb


【解决方案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 的方式,因为它反映了我对整个过程的看法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    相关资源
    最近更新 更多