Interface Datastore

    • Method Detail

      • newTransaction

        Transaction newTransaction​(TransactionOptions options)
        Returns a new Datastore transaction.
        Parameters:
        options - a transaction option indicating the mode of the transaction (read-only or read-write)
        Throws:
        DatastoreException - upon failure
      • runInTransaction

        <T> T runInTransaction​(Datastore.TransactionCallable<T> callable)
        Invokes the callback's Datastore.TransactionCallable.run(com.google.cloud.datastore.DatastoreReaderWriter) method with a DatastoreReaderWriter that is associated with a new transaction. The transaction will be committed upon successful invocation. Any thrown exception will cause the transaction to rollback and will be propagated as a DatastoreException with the original exception as its root cause.

        Example of running in a transaction.

        
         String callableResult = "my_callable_result";
         TransactionCallable<String> callable = new TransactionCallable<String>() {
           public String run(DatastoreReaderWriter readerWriter) {
             // use readerWriter to run in transaction
             return callableResult;
           }
         };
         String result = datastore.runInTransaction(callable);
         
        Parameters:
        callable - the callback to call with a newly created transactional readerWriter
        Throws:
        DatastoreException - upon failure
      • runInTransaction

        <T> T runInTransaction​(Datastore.TransactionCallable<T> callable,
                               TransactionOptions options)
        Invokes the callback's Datastore.TransactionCallable.run(com.google.cloud.datastore.DatastoreReaderWriter) method with a DatastoreReaderWriter that is associated with a new transaction. The transaction will be committed upon successful invocation. Any thrown exception will cause the transaction to rollback and will be propagated as a DatastoreException with the original exception as its root cause. If TransactionOptions is set to read-write mode, previous transaction Id in the options will be automatically populated each time a transaction is retried.

        Example of running in a transaction.

        
         String callableResult = "my_callable_result";
         TransactionCallable<String> callable = new TransactionCallable<String>() {
           public String run(DatastoreReaderWriter readerWriter) {
             // use readerWriter to run in transaction
             return callableResult;
           }
         };
        
         TransactionOptions options = TransactionOptions.newBuilder()
             .setReadWrite(TransactionOptions.ReadWrite
                 .getDefaultInstance())
             .build();
        
         String result = datastore.runInTransaction(callable, options);
         
        Parameters:
        callable - the callback to call with a newly created transactional readerWriter
        options - the Transaction options indicating whether the transaction mode is Read-only or Read-Write
        Throws:
        DatastoreException - upon failure
      • newBatch

        Batch newBatch()
        Returns a new Batch for processing multiple write operations in one request.

        Example of starting a new batch.

        
         String keyName1 = "my_key_name_1";
         String keyName2 = "my_key_name_2";
         Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
         Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
         Batch batch = datastore.newBatch();
         Entity entity1 = Entity.newBuilder(key1).set("name", "John").build();
         Entity entity2 = Entity.newBuilder(key2).set("title", "title").build();
         batch.add(entity1);
         batch.add(entity2);
         batch.submit();
         
      • allocateId

        Key allocateId​(IncompleteKey key)
        Allocate a unique id for the given key. The returned key will have the same information (projectId, kind, namespace and ancestors) as the given key and will have a newly assigned id.

        Example of allocating an id.

        
         KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
         IncompleteKey incompleteKey = keyFactory.newKey();
        
         // let cloud datastore automatically assign an id
         Key key = datastore.allocateId(incompleteKey);
         
        Throws:
        DatastoreException - upon failure
      • allocateId

        List<Key> allocateId​(IncompleteKey... keys)
        Returns a list of keys using the allocated ids ordered by the input.

        Example of allocating multiple ids in a single batch.

        
         KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
         IncompleteKey incompleteKey1 = keyFactory.newKey();
         IncompleteKey incompleteKey2 = keyFactory.newKey();
        
         // let cloud datastore automatically assign the ids
         List<Key> keys = datastore.allocateId(incompleteKey1, incompleteKey2);
         
        Throws:
        DatastoreException - upon failure
        See Also:
        allocateId(IncompleteKey)
      • reserveIds

        List<Key> reserveIds​(Key... keys)
        Reserve one or more keys, preventing them from being automatically allocated by Datastore.

        Example of reserving multiple ids in a single batch.

        
         KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
         Key key1 = keyFactory.newKey(10);
         Key key2 = keyFactory.newKey("name");
         List<Key> keys = datastore.reserveIds(key1, key2);
        
         
        Throws:
        DatastoreException - upon failure
      • add

        Entity add​(FullEntity<?> entity)
        Datastore add operation: inserts the provided entity. This method will automatically allocate an id if necessary.

        If an entity for entity.getKey() does not exist, entity is inserted. Otherwise, a DatastoreException is thrown with BaseServiceException.getReason() equal to "ALREADY_EXISTS".

        Example of adding a single entity.

        
         String keyName = "my_key_name";
         Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
         Entity.Builder entityBuilder = Entity.newBuilder(key);
         entityBuilder.set("propertyName", "value");
         Entity entity = entityBuilder.build();
         try {
           datastore.add(entity);
         } catch (DatastoreException ex) {
           if ("ALREADY_EXISTS".equals(ex.getReason())) {
             // entity.getKey() already exists
           }
         }
         
        Specified by:
        add in interface DatastoreWriter
        Parameters:
        entity - the entity to add
        Returns:
        an Entity with the same properties and a key that is either newly allocated or the same one if key is already complete
        Throws:
        DatastoreException - upon failure or if an entity for entity.getKey() already exists
      • add

        List<Entity> add​(FullEntity<?>... entities)
        Datastore add operation: inserts the provided entities. This method will automatically allocate id for any entity with an incomplete key.

        If none of entities' keys exist, all entities are inserted. If any of entities' keys already exists the method throws a DatastoreException with BaseServiceException.getReason() equal to "ALREADY_EXISTS". All entities in entities whose key did not exist are inserted. To achieve a transactional behavior, use Transaction.

        Example of adding multiple entities.

        
         String keyName1 = "my_key_name1";
         String keyName2 = "my_key_name2";
         Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
         Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
         entityBuilder1.set("propertyName", "value1");
         Entity entity1 = entityBuilder1.build();
        
         Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
         Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
         entityBuilder2.set("propertyName", "value2");
         Entity entity2 = entityBuilder2.build();
        
         try {
           datastore.add(entity1, entity2);
         } catch (DatastoreException ex) {
           if ("ALREADY_EXISTS".equals(ex.getReason())) {
             // at least one of entity1.getKey() and entity2.getKey() already exists
           }
         }
         
        Specified by:
        add in interface DatastoreWriter
        Returns:
        a list of Entity ordered by input with the same properties and a key that is either newly allocated or the same one if was already complete
        Throws:
        DatastoreException - upon failure or if any of entities' keys already exists
        See Also:
        DatastoreWriter.add(FullEntity)
      • update

        void update​(Entity... entities)
        A Datastore update operation. The operation will fail if an entity with the same key does not already exist.

        Example of updating multiple entities.

        
         String keyName1 = "my_key_name_1";
         String keyName2 = "my_key_name_2";
         Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
         Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
         entityBuilder1.set("propertyName", "updatedValue1");
         Entity entity1 = entityBuilder1.build();
        
         Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
         Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
         entityBuilder2.set("propertyName", "updatedValue2");
         Entity entity2 = entityBuilder2.build();
        
         datastore.update(entity1, entity2);
         
        Specified by:
        update in interface DatastoreWriter
        Throws:
        DatastoreException - upon failure
      • put

        Entity put​(FullEntity<?> entity)
        A Datastore put (a.k.a upsert) operation: inserts an entity if it does not exist, updates it otherwise. This method will automatically allocate an id if necessary.

        Example of putting a single entity.

        
         String keyName = "my_key_name";
         Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
         Entity.Builder entityBuilder = Entity.newBuilder(key);
         entityBuilder.set("propertyName", "value");
         Entity entity = entityBuilder.build();
         datastore.put(entity);
         
        Specified by:
        put in interface DatastoreWriter
        Parameters:
        entity - the entity to put
        Returns:
        an Entity with the same properties and a key that is either newly allocated or the same one if key is already complete
        Throws:
        DatastoreException - upon failure
      • put

        List<Entity> put​(FullEntity<?>... entities)
        A Datastore put (a.k.a upsert) operation: creates an entity if it does not exist, updates it otherwise. This method will automatically allocate id for any entity with an incomplete key.

        Example of putting multiple entities.

        
         String keyName1 = "my_key_name1";
         String keyName2 = "my_key_name2";
         Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
         Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
         entityBuilder1.set("propertyName", "value1");
         Entity entity1 = entityBuilder1.build();
        
         Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
         Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
         entityBuilder2.set("propertyName", "value2");
         Entity entity2 = entityBuilder2.build();
        
         datastore.put(entity1, entity2);
         
        Specified by:
        put in interface DatastoreWriter
        Returns:
        a list of updated or inserted Entity, ordered by input. Returned keys are either newly allocated or the same one if was already complete.
        Throws:
        DatastoreException - upon failure
      • delete

        void delete​(Key... keys)
        A datastore delete operation. It is OK to request the deletion of a non-existing key.

        Example of deleting multiple entities.

        
         String keyName1 = "my_key_name1";
         String keyName2 = "my_key_name2";
         Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
         Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
         datastore.delete(key1, key2);
         
        Specified by:
        delete in interface DatastoreWriter
        Throws:
        DatastoreException - upon failure
      • newKeyFactory

        KeyFactory newKeyFactory()
        Returns a new KeyFactory for this service

        Example of creating a KeyFactory.

        
         KeyFactory keyFactory = datastore.newKeyFactory();
         
      • get

        Entity get​(Key key,
                   ReadOption... options)
        Returns an Entity for the given Key or null if it doesn't exist. ReadOptions can be specified if desired.

        Example of getting an entity.

        
         String keyName = "my_key_name";
         Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
         Entity entity = datastore.get(key);
         // Do something with the entity
         
        Throws:
        DatastoreException - upon failure
      • get

        Iterator<Entity> get​(Iterable<Key> keys,
                             ReadOption... options)
        Returns an Entity for each given Key that exists in the Datastore. The order of the result is unspecified. Results are loaded lazily, so it is possible to get a DatastoreException from the returned Iterator's hasNext or next methods. ReadOptions can be specified if desired.

        Example of getting multiple entity objects.

        
         String firstKeyName = "my_first_key_name";
         String secondKeyName = "my_second_key_name";
         KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
         Key firstKey = keyFactory.newKey(firstKeyName);
         Key secondKey = keyFactory.newKey(secondKeyName);
         Iterator<Entity> entitiesIterator = datastore.get(Lists.newArrayList(firstKey, secondKey));
         List<Entity> entities = Lists.newArrayList();
         while (entitiesIterator.hasNext()) {
           Entity entity = entitiesIterator.next();
           // do something with the entity
           entities.add(entity);
         }
         
        Throws:
        DatastoreException - upon failure
        See Also:
        DatastoreReader.get(Key)
      • fetch

        List<Entity> fetch​(Iterable<Key> keys,
                           ReadOption... options)
        Returns a list with a value for each given key (ordered by input). null values are returned for nonexistent keys. When possible prefer using DatastoreReader.get(Key...) to avoid eagerly loading the results. ReadOptions can be specified if desired.

        Example of fetching a list of Entity objects.

        
         String firstKeyName = "my_first_key_name";
         String secondKeyName = "my_second_key_name";
         KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
         Key firstKey = keyFactory.newKey(firstKeyName);
         Key secondKey = keyFactory.newKey(secondKeyName);
         List<Entity> entities = datastore.fetch(Lists.newArrayList(firstKey, secondKey));
         for (Entity entity : entities) {
           // do something with the entity
         }
         
      • run

        <T> QueryResults<T> run​(Query<T> query,
                                ReadOption... options)
        Submits a Query and returns its result. ReadOptions can be specified if desired.

        Example of running a query to find all entities of one kind.

        
         String kind = "my_kind";
         StructuredQuery<Entity> query = Query.newEntityQueryBuilder()
             .setKind(kind)
             .build();
         QueryResults<Entity> results = datastore.run(query);
         List<Entity> entities = Lists.newArrayList();
         while (results.hasNext()) {
           Entity result = results.next();
           // do something with result
           entities.add(result);
         }
         

        Example of running a query to find all entities with a matching property value.

        
         String kind = "my_kind";
         String property = "my_property";
         String value = "my_value";
         StructuredQuery<Entity> query = Query.newEntityQueryBuilder()
             .setKind(kind)
             .setFilter(PropertyFilter.eq(property, value))
             .build();
         QueryResults<Entity> results = datastore.run(query);
         List<Entity> entities = Lists.newArrayList();
         while (results.hasNext()) {
           Entity result = results.next();
           // do something with result
           entities.add(result);
         }
         
        Throws:
        DatastoreException - upon failure
      • runAggregation

        default AggregationResults runAggregation​(AggregationQuery query,
                                                  ReadOption... options)
        Submits a AggregationQuery and returns AggregationResults. ReadOptions can be specified if desired.

        Example of running an AggregationQuery to find the count of entities of one kind.

        StructuredQuery example:

        
         EntityQuery selectAllQuery = Query.newEntityQueryBuilder()
            .setKind("Task")
            .build();
         AggregationQuery aggregationQuery = Query.newAggregationQueryBuilder()
            .addAggregation(count().as("total_count"))
            .over(selectAllQuery)
            .build();
         AggregationResults aggregationResults = datastore.runAggregation(aggregationQuery);
         for (AggregationResult aggregationResult : aggregationResults) {
             System.out.println(aggregationResult.get("total_count"));
         }
         

        GqlQuery example:

        
         GqlQuery<?> selectAllGqlQuery = Query.newGqlQueryBuilder(
                 "AGGREGATE COUNT(*) AS total_count, COUNT_UP_TO(100) AS count_upto_100 OVER(SELECT * FROM Task)"
             )
             .setAllowLiteral(true)
             .build();
         AggregationQuery aggregationQuery = Query.newAggregationQueryBuilder()
             .over(selectAllGqlQuery)
             .build();
         AggregationResults aggregationResults = datastore.runAggregation(aggregationQuery);
         for (AggregationResult aggregationResult : aggregationResults) {
           System.out.println(aggregationResult.get("total_count"));
           System.out.println(aggregationResult.get("count_upto_100"));
         }
         
        Returns:
        AggregationResults
        Throws:
        DatastoreException - upon failure