user3690321
user3690321

Reputation: 65

Check for duplicated in gae datastore

I'm creating an Entity for every add command that I input but I want to know that how can I check for duplicates in the datastore?

    Entity entity = new Entity("Animal");
    entity.setProperty("nameOfAnimal",name_of_animal);

I want to check is if for the second time there is an animal which is entered with the same name, how do I check for a duplicate entry?

Upvotes: 0

Views: 219

Answers (3)

tx802
tx802

Reputation: 3564

You have a number of options depending on what behaviour you are looking for.

If you use your nameOfAnimal as the entity's name, you can simply try fetching the entity by key before you create a new one:

Key animalKey = KeyFactory.createKey("Animal", "fox");
Entity fox;
try {
    fox = datastoreService.get(animalKey);
    // no exception thrown so fox already exists
    throw new RuntimeException("Animal already exists!");
}
catch(EntityNotFoundException e) {
    // no duplicates, so can create
    fox = new Entity(animalKey);
    fox.setNoise("unknown");
    datastoreService.put(fox);
}

If you're not using the nameOfAnimal as the key, you can use a Query("Animal") instead of the get() (as in the answer from eluleci).

Either way, beware there's a potential race condition there. If you want to make it safe, you'll need to wrap it in a transaction, otherwise you may find two threads competing to create the first fox (for example), with one potentially overwriting the other.

Upvotes: 1

Omair Shamshir
Omair Shamshir

Reputation: 2136

you can use the name of the animal as 'id' of the entity , and then use get by id to check whether this animal name exists or not.

Upvotes: 0

eluleci
eluleci

Reputation: 3529

You can get try to get the entities by filtering the "nameOfAnimal" property and check the returned result. If the result is empty it means there is no entity yet.

Filter propertyFilter =
  new FilterPredicate("nameOfAnimal", FilterOperator.EQUAL, name_of_animal);
Query q = new Query("Animal").setFilter(propertyFilter);
PreparedQuery pq = datastore.prepare(q);
List<Animal> resultList = pq.asList(FetchOptions.Builder.withLimit(1));
if(resultList.size() > 0) {
    // same name exists
} else {
    // first entitiy with this name
}

The code is not tested but this is the main idea. Here is the documentation for property filters.

Upvotes: 0

Related Questions