user3358218 user3358218 - 2 months ago 20
Java Question

How to check if an entity exists in the Datastore in Java?

Okay, the scenario is the following:

I have an Entity of kind

Email
with a property
name
:

Entity email = new Entity("Email");
email.setProperty("name", "John");
datastore.put(email);


What I want to check is if exists an entity of kind
Email
with the property
name
equal to
John
. It is possible to make that in Java?

Thank you.

Answer

Property "name" is indexed, so you can run a query on Email entity to check if an entity (or entities) with this name already exist. For example:

Query q = new Query("Email");
q.setFilter(new FilterPredicate("name", FilterOperator.EQUAL, "John");
List<Entity> entities = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
if (entities.isEmpty()) {
    // no entities with name "John"
}