user3358218
user3358218

Reputation: 5

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.

Upvotes: 0

Views: 1107

Answers (1)

Andrei Volgin
Andrei Volgin

Reputation: 41089

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"
}

Upvotes: 1

Related Questions