Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple entities from GAE datastore by keys

I am using Google App Engine on localhost. I have 2000 entities of kind Book in the Datastore. I want to delete the first 1900 (the keys range from 1 to 1901). How would I do that from the interactive console? I am using ndb as opposed to db

Maybe there is some sort of range functionality.

For example, I try the following, but nothing happens.

from myddb import Book

list= Book.gql("WHERE ID < 193")

for entity in list:
  db.delete(entity) 

EDIT:

Based on response from @Lipis the following is working

from myddb import Book

from google.appengine.ext import ndb

book_keys = Book.query().fetch(keys_only=True)
ndb.delete_multi(book_keys)

But that deletes everything. What I need to work is query by Key aka ID like

book_keys = Book.query(Article._Key < 1901).fetch(keys_only=True)
like image 459
learner Avatar asked Dec 11 '22 17:12

learner


2 Answers

You should use the ndb.delete_multi():

from google.appengine.ext import ndb

book_keys = Book.query().fetch(keys_only=True)
ndb.delete_multi(book_keys)

You should go through the NDB Queries to see what other options you have and what you can achieve.

like image 133
Lipis Avatar answered Mar 03 '23 03:03

Lipis


EDIT

I have not tested the solution below but test it and let me know.

Also this should help greatly ndb cheat sheet

q = Book.query(default_options=QueryOptions(keys_only=True))

   if Book.ID < 1901:
      ndb.delete_multi([m.key for m in q.fetch(1900)])
like image 33
Tkingovr Avatar answered Mar 03 '23 02:03

Tkingovr