Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RethinkDB: how to do real upsert - insert new document on update fail?

Tags:

rethinkdb

I want to insert new document on update fail - is there any way to do this? Now RethinkDB allows me only to update document on insert fail via {upsert: true} in insert command.

like image 460
La Faulx Avatar asked Oct 02 '22 21:10

La Faulx


1 Answers

You can use replace with a branch and an explicit merge.

replace is like update, except it completely replaces a document rather than merging with it. The following are equivalent (in Ruby code):

table.get(id).update{|row| {a: row['a']+1}}
table.get(id).replace{|row| row.merge({a: row['a']+1})}

So if you want to do an "update", or else insert a row if there is no row, you could do this:

table.get(id).replace {|row|
  r.branch(
    row.eq(nil),
    INSERT_OBJECT,
    row.merge(UPDATE_OBJECT))
}
like image 133
mlucy Avatar answered Oct 05 '22 11:10

mlucy