/** Example of putting a single entity. */ // [TARGET put(FullEntity)] // [VARIABLE "my_key_name"] public void putSingleEntity(String keyName) { Datastore datastore = transaction.getDatastore(); // [START putSingleEntity] Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); Entity.Builder entityBuilder = Entity.newBuilder(key); entityBuilder.set("propertyName", "value"); Entity entity = entityBuilder.build(); transaction.put(entity); transaction.commit(); // [END putSingleEntity] }
KeyFactory keyFactory = datastore.newKeyFactory().setKind("Person"); Key key = keyFactory.newKey("john.doe@gmail.com"); Entity entity = Entity.newBuilder(key) .set("name", "John Doe") .set("age", 51) .set("favorite_food", "pizza") .build(); datastore.put(entity); Key janeKey = keyFactory.newKey("jane.doe@gmail.com"); Entity janeEntity = Entity.newBuilder(janeKey) .set("name", "Jane Doe") .set("age", 44) Key joeKey = keyFactory.newKey("joe.shmoe@gmail.com"); Entity joeEntity = Entity.newBuilder(joeKey) .set("name", "Joe Shmoe") .set("age", 27) .build(); QueryResults<Entity> results = datastore.run(query); while (results.hasNext()) { Entity currentEntity = results.next(); System.out.println(currentEntity.getString("name") + ", you're invited to a pizza party!");
Preconditions.checkArgument(entity.hasKey(), "Entity %s is missing a key", entity); if (entity.getKey() instanceof Key) { Entity completeEntity = Entity.convert((FullEntity<Key>) entity); dedupEntities.put(completeEntity.getKey(), completeEntity); } else { mutationsPb.add( com.google.datastore.v1.Mutation.newBuilder().setUpsert(entity.toPb()).build()); } else { responseBuilder.add( Entity.newBuilder(Key.fromPb(mutationResults.next().getKey()), entity).build());
private static Map<String, Object> getProperties(Entity entity) throws IOException, ClassNotFoundException { if (entity == null) { return null; } ImmutableMap.Builder<String, Object> builder = new ImmutableMap.Builder<>(); for (String property : entity.getNames()) { // builder.put(property, entity.getValue(property)); if (entity.getValue(property) instanceof StringValue) { builder.put(property, (String) entity.getString(property)); } else if (entity.getValue(property) instanceof LongValue) { // This conversion is safe because of integer to long conversion above builder.put(property, new Long(entity.getLong(property)).intValue()); } else if (entity.getValue(property) instanceof DoubleValue) { builder.put(property, (Double) entity.getDouble(property)); } else if (entity.getValue(property) instanceof BooleanValue) { builder.put(property, (Boolean) entity.getBoolean(property)); } else if (entity.getValue(property) instanceof TimestampValue) { builder.put(property, (Timestamp) entity.getTimestamp(property)); } else { Blob blob = entity.getBlob(property); Object obj = null; try (ObjectInputStream in = new ObjectInputStream(blob.asInputStream())) { obj = in.readObject(); } builder.put(property, obj); // BlobValue } } return builder.build(); }
public static void main(String... args) { Datastore datastore = DatastoreOptions.getDefaultInstance().getService(); KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind"); Key key = keyFactory.newKey("keyName"); Entity entity = datastore.get(key); if (entity != null) { System.out.println("Updating access_time for " + entity.getString("name")); entity = Entity.newBuilder(entity).set("access_time", Timestamp.now()).build(); datastore.update(entity); } } }
@Override public void update(Entity... entities) { if (entities.length > 0) { List<com.google.datastore.v1.Mutation> mutationsPb = new ArrayList<>(); Map<Key, Entity> dedupEntities = new LinkedHashMap<>(); for (Entity entity : entities) { dedupEntities.put(entity.getKey(), entity); } for (Entity entity : dedupEntities.values()) { mutationsPb.add( com.google.datastore.v1.Mutation.newBuilder().setUpdate(entity.toPb()).build()); } commitMutation(mutationsPb); } }
/** Example of putting a single entity. */ // [TARGET put(FullEntity)] // [VARIABLE "my_key_name"] public void putSingleEntity(String keyName) { // [START putSingleEntity] 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); // [END putSingleEntity] }
@Test public void testTransactionWithQuery() { Query<Entity> query = Query.newEntityQueryBuilder() .setKind(KIND2) .setFilter(PropertyFilter.hasAncestor(KEY2)) .build(); Transaction transaction = datastore.newTransaction(); QueryResults<Entity> results = transaction.run(query); assertEquals(ENTITY2, results.next()); assertFalse(results.hasNext()); transaction.add(ENTITY3); transaction.commit(); assertEquals(ENTITY3, datastore.get(KEY3)); transaction = datastore.newTransaction(); results = transaction.run(query); assertEquals(ENTITY2, results.next()); transaction.delete(ENTITY3.getKey()); // update entity2 during the transaction datastore.put(Entity.newBuilder(ENTITY2).clear().build()); try { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException expected) { assertEquals("ABORTED", expected.getReason()); } }
@Test public void testNewTransactionCommit() { Transaction transaction = DATASTORE.newTransaction(); transaction.add(ENTITY3); Entity entity2 = Entity.newBuilder(ENTITY2).clear().setNull("bla").build(); transaction.update(entity2); transaction.delete(KEY1); transaction.commit(); assertFalse(transaction.isActive()); List<Entity> list = DATASTORE.fetch(KEY1, KEY2, KEY3); assertNull(list.get(0)); assertEquals(entity2, list.get(1)); assertEquals(ENTITY3, list.get(2)); assertEquals(3, list.size()); try { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException expected) { assertEquals("FAILED_PRECONDITION", expected.getReason()); } try { transaction.rollback(); fail("Expecting a failure"); } catch (DatastoreException expected) { assertEquals("FAILED_PRECONDITION", expected.getReason()); } }
public static void main(String... args) throws Exception { // Instantiates a client Datastore datastore = DatastoreOptions.getDefaultInstance().getService(); // The kind for the new entity String kind = "Task"; // The name/ID for the new entity String name = "sampletask1"; // The Cloud Datastore key for the new entity Key taskKey = datastore.newKeyFactory().setKind(kind).newKey(name); // Prepares the new entity Entity task = Entity.newBuilder(taskKey) .set("description", "Buy milk") .build(); // Saves the entity datastore.put(task); System.out.printf("Saved %s: %s%n", task.getKey().getName(), task.getString("description")); //Retrieve entity Entity retrieved = datastore.get(taskKey); System.out.printf("Retrieved %s: %s%n", taskKey.getName(), retrieved.getString("description")); } }
/** * Return a list of all users. */ public List<User> getAllUsers() { Query<Entity> query = Query.newGqlQueryBuilder(Query.ResultType.ENTITY, "SELECT * FROM " + kind).build(); QueryResults<Entity> results = datastore.run(query); List<User> users = new ArrayList<>(); while (results.hasNext()) { Entity result = results.next(); users.add( new User(result.getString("id"), result.getString("name"), result.getString("email"))); } return users; }
/** Example of adding a single entity. */ // [TARGET add(FullEntity)] // [VARIABLE "my_key_name"] public void addSingleEntity(String keyName) { Datastore datastore = transaction.getDatastore(); // [START addSingleEntity] Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); Entity.Builder entityBuilder = Entity.newBuilder(key); entityBuilder.set("propertyName", "value"); Entity entity = entityBuilder.build(); transaction.add(entity); transaction.commit(); // [END addSingleEntity] }
@Test public void testTransactionWithRead() { Transaction transaction = datastore.newTransaction(); assertNull(transaction.get(KEY3)); transaction.add(ENTITY3); transaction.commit(); assertEquals(ENTITY3, datastore.get(KEY3)); transaction = datastore.newTransaction(); assertEquals(ENTITY3, transaction.get(KEY3)); // update entity3 during the transaction datastore.put(Entity.newBuilder(ENTITY3).clear().build()); transaction.update(ENTITY2); try { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException expected) { assertEquals("ABORTED", expected.getReason()); } }
/** Example of updating multiple entities. */ // [TARGET update(Entity...)] // [VARIABLE "my_key_name1"] // [VARIABLE "my_key_name2"] public void multipleUpdateEntities(String keyName1, String keyName2) { Datastore datastore = transaction.getDatastore(); // [START multipleUpdateEntities] Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); Entity.Builder entityBuilder1 = Entity.newBuilder(key1); entityBuilder1.set("propertyName", "value3"); Entity entity1 = entityBuilder1.build(); Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); Entity.Builder entityBuilder2 = Entity.newBuilder(key2); entityBuilder2.set("propertyName", "value4"); Entity entity2 = entityBuilder2.build(); transaction.update(entity1, entity2); transaction.commit(); // [END multipleUpdateEntities] }
if (user.contains("contact")) { FullEntity<IncompleteKey> contact = user.getEntity("contact"); String email = contact.getString("email"); String phone = contact.getString("phone"); System.out.printf( "User '%s' email is '%s', phone is '%s'.%n", userKey.getName(), email, phone); System.out.printf("User '%s' has %d comment[s].%n", userKey.getName(), user.getLong("count")); int limit = 200; Map<Timestamp, String> sortedComments = new TreeMap<>(); .build(); while (true) { QueryResults<Entity> results = tx.run(query); int resultCount = 0; while (results.hasNext()) { Entity result = results.next(); sortedComments.put(result.getTimestamp("timestamp"), result.getString("content")); resultCount++; break; query = query.toBuilder().setStartCursor(results.getCursorAfter()).build();
@Override public <T extends DataModel> void update(UUID jobId, String key, T model) { Transaction transaction = datastore.newTransaction(); Key entityKey = getDataKey(jobId, key); try { Entity previousEntity = transaction.get(entityKey); if (previousEntity == null) { throw new IOException("Could not find record for data key: " + entityKey.getName()); } String serialized = objectMapper.writeValueAsString(model); Entity entity = Entity.newBuilder(entityKey) .set(CREATED_FIELD, Timestamp.now()) .set(model.getClass().getName(), serialized) .build(); transaction.put(entity); transaction.commit(); } catch (IOException t) { transaction.rollback(); throw new RuntimeException("Failed atomic update of key: " + key, t); } }
/** * Marks a task entity as done. * * @param id The ID of the task entity as given by {@link Key#id()} * @return true if the task was found, false if not * @throws DatastoreException if the transaction fails */ boolean markDone(long id) { Transaction transaction = datastore.newTransaction(); try { Entity task = transaction.get(keyFactory.newKey(id)); if (task != null) { transaction.put(Entity.newBuilder(task).set("done", true).build()); } transaction.commit(); return task != null; } finally { if (transaction.isActive()) { transaction.rollback(); } } } // [END datastore_update_entity]
/** Example of updating multiple entities. */ // [TARGET update(Entity...)] // [VARIABLE "my_key_name_1"] // [VARIABLE "my_key_name_2"] public void batchUpdateEntities(String keyName1, String keyName2) { // [START batchUpdateEntities] 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); // [END batchUpdateEntities] }
/** Example of starting a new batch. */ // [TARGET newBatch()] // [VARIABLE "my_key_name_1"] // [VARIABLE "my_key_name_2"] public Batch newBatch(String keyName1, String keyName2) { // [START newBatch] 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(); // [END newBatch] return batch; }
/** Example of adding a single entity. */ // [TARGET add(FullEntity)] // [VARIABLE "my_key_name"] public void addSingleEntity(String keyName) { // [START addSingleEntity] 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 } } // [END addSingleEntity] }