5

What is the idiomatic way for doing an 'insert if not exists'?

Can this be done without transactions?

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111

3 Answers3

3

Try this:

with upsert creates a record if it doesn't exists, unless it updates

var OrientDB = require('orientjs');

 var server = OrientDB({

     host: 'localhost',
     port: 2424,
     username: 'root',
     password: 'root'

 });

 var db = server.use({

     name:  'GratefulDeadConcerts',
     username: 'root',
     password: 'root'

 })

 db.query('UPDATE V SET id = 23 UPSERT WHERE id = 23')
 .then(function (response) {
    console.log(response);
});

 server.close();

Hope it helps.

Regards

Michela Bonizzi
  • 2,622
  • 1
  • 9
  • 16
  • Thank you for the reply. An upsert is not exactly the same semantics I'm looking for. An update will create a new version of the document, even if all the data is the same. What I'm looking for is a way to check if a record exists, by id, and then doing an insert if it doesn't. It should be a `noop` if the record does exist. – Bradley Serbu Aug 29 '16 at 20:18
1

You can use this code for example

db.query('select from v where rid = 23')
    .then(function (record) {
        if(record.length==0){
            db.query('insert into v(rid) values (23)');
        }
 });

Hope it helps.

Alessandro Rota
  • 3,560
  • 1
  • 8
  • 10
  • This is the way I am doing it now, but it's not a truly atomic operation. I'm attempting to using OrientDB for a high volume streaming backend, and there are still edge cases where duplicates are received off the stream and both attempt to insert. This causes a duplicate key issue with the index. – Bradley Serbu Aug 30 '16 at 20:57
0

If the data is quite small (that you can hold in memory in the server), you can do 1 get call to fetch all the data and do a batch insert only for those which are not already there.

If your creation data is very huge (that exceeds the runtime memory), you will have to follow Alessandro's method (which will be slow because for each insertion you'll have to check).

cegprakash
  • 2,937
  • 33
  • 60