Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google App Engine NDB - "Update or Insert (if not exists)"

I am trying to do the equivalent of an "Update or Insert (if not exists)".

Any idea how to do this? The only solution I can come up with was to do a GQL query, then either update returned records, or create a new one if none was returned from the query.

This method would not be atomic - but I am wondering if there was a "simple" way to do this.

like image 601
Brad Avatar asked Oct 02 '22 23:10

Brad


2 Answers

There are no atomic operations as such. You need to use transactions.

How about reading the docs, both db and ndb have a method for 'get or insert' which is transactional and then you do the update/apply of values to properties inside a transaction and then write (put()) the entity.

https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_get_or_insert

Also remember queries results are subject to "eventual" consistency unless they are ancestor queries.

Read more about transactions https://developers.google.com/appengine/docs/python/ndb/transactions

like image 91
Tim Hoffman Avatar answered Oct 12 '22 10:10

Tim Hoffman


If you have the key, just get, update, and put within a transaction. There's no "update" operation in GAE's datastore, it's just read the entity, and write the entity.

like image 38
dragonx Avatar answered Oct 12 '22 11:10

dragonx