RethinkDB 原子更新

RethinkDB atomic upsert

如何在 RethinkDB 中执行原子更新插入?例如,带有 url (id) 和点击次数 (count) 的 table。根据文档,我应该使用 {conflict: 'update'},所以我尝试了以下操作:

r.db('test').table('urls').insert({
  id: 'google.com',
  count: r.row('count').add(1).default(1),
  // ... lots of other fields ...
}, {
  conflict: 'update' 
});

这个returns错误r.row is not defined in this context。我在他们的 github 存储库中看到一个问题,其中 danielmewes 建议 .get(...).replace(...) 以实现此目的,但是替换整个文档以更新字段不会很昂贵吗?如果 get 不存在,我可以使用 get 后跟 updateinsert,但这可能会导致竞争条件,因为会有多个进程写入此 table.感谢您的帮助!

是的,方法是使用 replace 来处理文档不存在的情况。当您现在更新一个字段时,RethinkDB 总是会重写整个文档,因此您不必担心 replace 由于这个原因性能会变差。