Search code examples
pythongoogle-app-enginegoogle-cloud-platformgoogle-cloud-datastoreapp-engine-ndb

How to delete data from datastore using NDB query in python?


I have data like this:

{
  "queryValue": "SELECT Name, Site, Phone, Type, Owner.Name, CreatedBy.profile.Name FROM Account",
  "SFDCUser_id": "0056F00000ALw6aQAD",
  "updated_at": "2018-11-18T07:26:24.954000",
  "id": "aghkZXZ-Tm9uZXIZCxIMUXVlcnlIaXN0b3J5GICAgICAyOsKDA",
  "is_error": false,
  "nid": 6102564412063744,
  "date": "2018-11-18T07:26:24.954000",
  "created_at": "2018-11-18T07:26:24.954000"
}

And I am using id to delete specific record from datastore. My code is like this:

ndb.Key('id',id).delete()

But its not working right, I am new to python.


Solution

  • Well, you're not "building" the key properly. The key should be built using the entity kind and its ID/name (if you know it). From Specifying your own key name:

    account.key = ndb.Key('Account', '[email protected]')
    
    # You can also use the model class object itself, rather than its name,
    # to specify the entity's kind: 
    account.key = ndb.Key(Account, '[email protected]')
    

    But that example assumes '[email protected]' was specified to be the key's ID/name when the entity was created.

    The entity you show appears to be of the Account kind (or at least that's what you queried for), not of an id kind. So you should build you key just like in the quoted example (their entity kind was also named Account).

    Also it doesn't appear that specified entity IDs were used for your entity:

    • the entity's id value looks like a key's urlsafe string:

      "id": "aghkZXZ-Tm9uZXIZCxIMUXVlcnlIaXN0b3J5GICAgICAyOsKDA"

    • there's a nid value which looks like a datastore auto-generated numeric key ID:

      "nid": 6102564412063744

    If so then nid is actually your key ID, so you'd be building your key like this:

    ndb.Key(Account, nid)
    

    You could also use:

    ndb.Key(urlsafe=id)
    

    But if you actually have the entity, from the query results for example, you no longer need to build its key to perform the deletion, you can obtain the key directly from the entity and delete it like this:

    for entity in ndb.query(...).fetch(...):
        entity.key.delete()
    

    If you have multiple entities to delete it's more efficient to use ndb.delete_multi(), see Deleting entities in bulk.