将 RethinkDB 表和对象创建命令与 rethinkdbdash 正确链接



我正在处理一个文本数据流,我事先不知道其值的分布是什么,但我知道每个看起来像这样:

{
  "datetime": "1986-11-03T08:30:00-07:00",
  "word": "wordA",
  "value": "someValue"
}

我正在尝试根据它的值将其分类到 RethinkDB 对象中,其中对象如下所示:

{
  "bucketId": "1",
  "bucketValues": {
    "wordA": [
      {"datetime": "1986-11-03T08:30:00-07:00"},
      {"datetime": "1986-11-03T08:30:00-07:00"}
    ],
    "wordB": [
      {"datetime": "1986-11-03T08:30:00-07:00"},
      {"datetime": "1986-11-03T08:30:00-07:00"}
    ]
  }
}

目的是最终计算每个存储桶中每个单词的出现次数。

由于我正在处理大约一百万个存储桶,并且事先不知道这些单词,因此计划是动态创建此对象。但是,我是 RethinkDB 的新手,我已经尽力以这样一种方式做到这一点,即我不尝试将word键添加到尚不存在的存储桶中,但我不完全确定我是否遵循最佳实践在这里链接命令,如下所示(请注意,我在 Node.js 服务器上运行它:

var bucketId = "someId";
var word = "someWordValue"
r.do(r.table("buckets").get(bucketId), function(result) {
  return r.branch(
    // If the bucket doesn't exist
    result.eq(null), 
    // Create it
    r.table("buckets").insert({
      "id": bucketId,
      "bucketValues" : {}
    }),
    // Else do nothing
    "Bucket already exists"
  );
})
.run()
.then(function(result) {
  console.log(result);
  r.table("buckets").get(bucketId)
  .do(function(bucket) {
    return r.branch(
      // if the word already exists
      bucket("bucketValues").keys().contains(word),
      // Just append to it (code not implemented yet)
      "Word already exists",
      // Else create the word and append it
      r.table("buckets").get(bucketId).update(
        {"bucketValues": r.object(word, [/*Put the timestamp here*/])}
      )
    );
  })
  .run()
  .then(function(result) {
    console.log(result);
  });
});

是否需要在此处执行运行两次,或者我是否偏离了您应该如何与 RethinkDB 正确链接在一起?我只是想确保在我深入研究之前我没有以错误/艰难的方式做到这一点。

您不必多次执行run,具体取决于您想要的内容。基本上,run()结束链并将查询发送到服务器。因此,我们做所有事情来构建查询,并以run()结束它以执行它。如果您使用run()两次,这意味着它被发送到服务器 2 次。

因此,如果我们可以仅使用 RethinkDB 函数进行所有处理,则只需调用 run 一次。但是,如果我们想使用客户端对数据进行某种后处理,那么我们别无选择。通常我尝试使用 RethinkDB 进行所有处理:使用控制结构、循环和匿名函数,我们可以在不让客户端做一些逻辑的情况下走得很远。

在您的情况下,可以使用官方驱动程序使用 NodeJS 重写查询:

var r = require('rethinkdb')
var bucketId = "someId2";
var word = "someWordValue2";
r.connect()
.then((conn) => {
  r.table("buckets").insert({
        "id": bucketId,
        "bucketValues" : {}
  })
  .do((result) => {
    // We don't care about result at all
    // We just want to ensure it's there
    return r.table('buckets').get(bucketId)
      .update(function(bucket) {
        return {
          'bucketValues': r.object(
                          word,
                          bucket('bucketValues')(word).default([])
                          .append(r.now()))
        }
      })
  })
  .run(conn)
  .then((result) => { conn.close() })
})

最新更新