An Introduction To The Datastore In Java

Storing Data

Essentially, the datastore is a highly replicated, highly reliable place to store data. However, it is not a SQL database that you may have experience with. Instead, the datastore stores Entities, which are grouped into categories called kinds. Each entity has a unique ID or name – Google App Engine can set a unique ID, or you can set a name in your application code.

To create an entity with a mail kind, we use this line (App Engine allocates a unique ID for us automatically):

Entity entity = new Entity("mail");

Entities can have properties, which are name/valid pairs. To add a property, do this:

entity.setProperty("subject", subject); //Key, then value.

Here’s a complete code example to create an entity, set properties, and store it:

Entity entity = new Entity("mail");//Creates the entity with a kind of "mail", GAE automatically allocates an ID
entity.setUnindexedProperty("from", from);
entity.setProperty("subject", subject);
entity.setProperty("add_date", new Date());//Records the date this entity was added.
DatastoreServiceFactory.getDatastoreService().put(entity);

Note the use of setUnindexedProperty. This method informs App Engine that we won’t be searching on this property, so don’t build a search index for it. This is useful to reduce the cost of storing entities.

Datastore Query

Querying the datastore is simple as well.

Here’s an example piece of code which queries for all Entities with the kind of mail, and requiring that all properties returned have the property add_date greater than the value stored in date_var :

Query q = new Query("mail");
Query.Filter query_filter = new Query.FilterPredicate("add_date", Query.FilterOperator.GREATER_THAN_OR_EQUAL, date_var);
q.setFilter(query_filter);
PreparedQuery pq = DatastoreServiceFactory.getDatastoreService().prepare(q);
List<Entity> results = pq.asList(FetchOptions.Builder.withDefaults());

From here, we can iterate through the List, retrieve each Entity, and conduct operations on each Entity:

for (int i = 0; i < results.size(); i++) {
    Entity entity = results.get(i);
    //Do anything needed with the information from each entity.
}

Deleting

And finally, here is how to delete an entity (entity is the Entity object being deleted).

Key key = entity.getKey();
DatastoreServiceFactory.getAsyncDatastoreService().delete(key);