Search code examples
google-app-enginegoogle-cloud-datastoreapp-engine-ndbgoogle-app-engine-python

Can't delete Datastore entities in google-app-engine


I tried to delete all datastore entities in two different ways but I get an error:

Try 1:

results = myDS().query().fetch()
for res in results:
    res.delete()

Try 2:

results = myDS().query().fetch()
ndb.delete_multi(results)

In both cases it fails and I get the error:

The server encountered an error and could not complete your request.

Any idea why?


Solution

  • In the results obtained from your queries you have actual entities.

    In the first try, to delete an entity, you need to call .delete() on the entity's key, not on the entity itself, see also Deleting entities:

    res.key.delete()
    

    Similarly, in the 2nd try, you need to pass entity keys, not entities, to ndb.delete_multi(), see also Using batch operations:

    ndb.delete_multi([r.key for r in results])
    

    But in both cases it's more efficient to directly obtain just the entity keys from the queries (you don't actually need the entities themselves to delete them). It's also cheaper as you'd be skipping datastore read ops. Your tries would look like this:

    keys = myDS().query().fetch(keys_only=True)
    for key in keys:
        key.delete()
    
    keys = myDS().query().fetch(keys_only=True, limit=500)  # up to 500 keys at a time
    ndb.delete_multi(keys)