RethinkDB中的批量更新

svs*_*svs 5 rethinkdb

我正在尝试根据哈希中的一些预先计算的值更新RethinkDB中的多个文档.即

给定一个stats带有主键的表,其中slug包含数据

[{slug: 'foo', stats: {}}, {slug:'bar', stats:{}}]
Run Code Online (Sandbox Code Playgroud)

给出一个像Hash这样的值的Hash

updated_stats = {
  'foo' => {a: 1, b: 2}, 
  'bar' => {a: 3, b: 4}
}
Run Code Online (Sandbox Code Playgroud)

我可以做这个

updated_stats.each{|k,v| 
  r.table('stats').get(k).update{|s| 
    { :stats => v } 
  }  
}
Run Code Online (Sandbox Code Playgroud)

那么,为什么我不能做以下事情呢?

r.table('stats').get_all(*updated_stats.keys).update{|s| 
  { :stats => updated_stats[s["slug"]] }  
}
Run Code Online (Sandbox Code Playgroud)

rql显示nil为updated_stats [s ["slug"]]的值.真的很感激任何帮助.谢谢.

Kyl*_*ris 6

对于寻找如何批量更新记录的人来说,这实际上很简单,但一点也不直观。

您实际上必须执行一段insert时间来指定是否存在任何冲突,以更新这些记录。您显然需要提供要更新的每条记录的 ID。

使用以下数据集:

|-------------|--------------|
|      id     |     title    |
|-------------|--------------|
|      1      |      fun     |
|-------------|--------------|
|      2      |      in      |
|-------------|--------------|
|      3      |      the     |
|-------------|--------------|
|      4      |      sun     |
|-------------|--------------|
Run Code Online (Sandbox Code Playgroud)

这是一个示例(javascript):

const new_data = [
    {id: 1, title: 'dancing'},
    {id: 4, title: 'rain'},
];

r.db('your_db').table('your_table').insert(new_data, {conflict: 'update'});
Run Code Online (Sandbox Code Playgroud)

结果将是:

|-------------|--------------|
|      id     |     title    |
|-------------|--------------|
|      1      |    dancing   |
|-------------|--------------|
|      2      |      in      |
|-------------|--------------|
|      3      |      the     |
|-------------|--------------|
|      4      |      rain    |
|-------------|--------------|
Run Code Online (Sandbox Code Playgroud)

但是,您应该注意的一个警告是,如果您表示new_data数组中当前不存在于表中的某些内容,它将被添加/插入

干杯!


neu*_*ino 5

这是一个棘手的问题.

首先是解决方案.

r.table('stats').get_all(*updated_stats.keys).update{|s| 
  { :stats => r.expr(updated_stats).get_field(s["slug"]) } 
}.run()
Run Code Online (Sandbox Code Playgroud)

然后updated_stats是一个ruby哈希,所以当你使用括号时,它是通常的括号运算符,并且由于updated_stats没有键s ["slug"],它返回nil.所以,你必须包装updated_statsr.expr().

然后在括号红宝石用于nth,get_field,slice等并给予一个变量时,不能猜测它应该使用哪一个.所以你必须明确说你想要使用get_field.我们将添加一个括号术语,它可以解决这个问题 - 请参阅https://github.com/rethinkdb/rethinkdb/issues/1179

对不起你碰到了这个!