How to Truncate a Google Apps Datastore (Java)

April 16th, 2009 § 0

It’s not super simple but possible to truncate your google apps datastore. Please, don’t do as I did and attempt to use the web GUI to delete page after page of data for anything over a few hundred Entities. Instead, use this simple servlet example after changing “myKindOfData” to your own type. It’d even be better if you spend a few minutes and improve the servlet so that it takes a parameter to supply for the “kind” of entity.

public class TruncateServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("myKindOfData");
ArrayList keys = new ArrayList();
for (Entity taskEntity : datastore.prepare(q).asIterable())
keys.add(taskEntity.getKey());
datastore.delete(keys);
}
}

What I learned doing this activity is that when you’re deleting many rows, you’ll want to first collect the keys, then supply the collection to the delete() method, as opposed to deleting in the query loop, which will time out on you. (GAE is very picky about how long web requests take). I like how GAE applies all these restrictions on us…it forces you to economize and avoid long running servlet requests. Don’t leave this servlet on an open URL for too long, anybody can come along and delete your data.

Where Am I?

You are currently browsing entries tagged with delete at The Web Semantic.