我正在处理一个文本数据流,在这些数据流中,我不知道其值的分布情况,但我知道每个数据都是这样的:
{
"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联系在一起的基础?在深入研究之前,我只想确保我没有做错/难做的事情。
发布于 2016-01-22 18:39:08
您不必多次执行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() })
})
https://stackoverflow.com/questions/34951529
复制相似问题