Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a rethinkdb atomic update if document exists, insert otherwise?

Tags:

rethinkdb

How to make a rethinkdb atomic update if document exists, insert otherwise?

I want to do something like:

var tab = r.db('agflow').table('test');
r.expr([{id: 1, n: 0, x: 11}, {id: 2, n: 0, x: 12}]).forEach(function(row){
  var _id = row('id');
  return r.branch(
    tab.get(_id).eq(null),  // 1
    tab.insert(row),        // 2 
    tab.get(_id).update(function(row2){return {n: row2('n').add(row('n'))}}) // 3
  )})

However this is not fully atomic, because between the time when we check if document exists (1) and inserting it (2) some other thread may insert it.

How to make this query atomic?

like image 515
Robert Zaremba Avatar asked Jun 19 '14 12:06

Robert Zaremba


1 Answers

I think the solution is passing

conflict="update"

to the insert method.

Als see RethinkDB documentation on insert

like image 67
wedesoft Avatar answered Sep 30 '22 19:09

wedesoft