Checking if Entity exists in google app engine datastore.

后端 未结 3 1817
感动是毒
感动是毒 2021-01-01 10:38

What is the best/fastest way to check if an Entity exists in a google-app-engine datastore? For now I\'m trying to get the entity by key and checking if the get() returns a

相关标签:
3条回答
  • com.google.appengine.api has been deprecated in favor of the App Engine GCS client.

    Have you considered using a query? Guess-and-check is not a scalable way to find out of an entity exists in a data store. A query can be created to retrieve entities from the datastore that meet a specified set of conditions:

    https://developers.google.com/appengine/docs/java/datastore/queries

    EDIT:

    What about the key-only query? Key-only queries run faster than queries that return complete entities. To return only the keys, use the Query.setKeysOnly() method.

    new Query("Kind").addFilter(Entity.KEY_RESERVED_PROPERTY, FilterOperator.EQUAL, key).setKeysOnly();
    

    Source: [1]: http://groups.google.com/group/google-appengine-java/browse_thread/thread/b1d1bb69f0635d46/0e2ba938fad3a543?pli=1

    0 讨论(0)
  • 2021-01-01 11:26

    What you proposed would indeed be the fastest way to know if your entity exists. The only thing slowing you down is the time it takes to fetch and deserialize your entity. If your entity is large, this can slow you down.

    IF this action (checking for existence) is a major bottleneck for you and you have large entities, you may want to roll your own system of checking by using two entities - first you would have your existing entity with data, and a second entity that either stores the reference to the real entity, or perhaps an empty entity where the key is just a variation on the original entity key that you can compute. You can check for existence quickly using the 2nd entity, and then fetch the first entity only if the data is necessary.

    The better way I think would just be to design your keys such they you know there would not be duplicates, or that your operations are idempotent, so that even if an old entity was overwritten, it wouldn't matter.

    0 讨论(0)
  • 2021-01-01 11:32

    You could fetch using a List<Key> containing only one Key, that method returns a Map<Key, Entity> which you can check if it contains an actual value or null, for example:

    Entity e = datastoreService.get(Arrays.asList(key)).get(key);
    

    In general though I think it'd be easier to wrap the get() in a try/catch that returns null if the EntityNotFoundException is caught.

    0 讨论(0)
提交回复
热议问题