com.google.cloud.datastore.IncompleteKey Java Examples
The following examples show how to use
com.google.cloud.datastore.IncompleteKey.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransactionSnippets.java From google-cloud-java with Apache License 2.0 | 6 votes |
/** Example of putting multiple entities with deferred id allocation. */ // [TARGET putWithDeferredIdAllocation(FullEntity...)] public List<Key> multiplePutEntitiesDeferredId() { Datastore datastore = transaction.getDatastore(); // [START multiplePutEntitiesDeferredId] IncompleteKey key1 = datastore.newKeyFactory().setKind("MyKind").newKey(); FullEntity.Builder entityBuilder1 = FullEntity.newBuilder(key1); entityBuilder1.set("propertyName", "value1"); FullEntity entity1 = entityBuilder1.build(); IncompleteKey key2 = datastore.newKeyFactory().setKind("MyKind").newKey(); FullEntity.Builder entityBuilder2 = FullEntity.newBuilder(key2); entityBuilder2.set("propertyName", "value2"); FullEntity entity2 = entityBuilder2.build(); transaction.putWithDeferredIdAllocation(entity1, entity2); Response response = transaction.commit(); // [END multiplePutEntitiesDeferredId] return response.getGeneratedKeys(); }
Example #2
Source File: TransactionSnippets.java From google-cloud-java with Apache License 2.0 | 6 votes |
/** Example of adding multiple entities with deferred id allocation. */ // [TARGET addWithDeferredIdAllocation(FullEntity...)] public List<Key> multipleAddEntitiesDeferredId() { Datastore datastore = transaction.getDatastore(); // [START multipleAddEntitiesDeferredId] IncompleteKey key1 = datastore.newKeyFactory().setKind("MyKind").newKey(); FullEntity.Builder entityBuilder1 = FullEntity.newBuilder(key1); entityBuilder1.set("propertyName", "value1"); FullEntity entity1 = entityBuilder1.build(); IncompleteKey key2 = datastore.newKeyFactory().setKind("MyKind").newKey(); FullEntity.Builder entityBuilder2 = FullEntity.newBuilder(key2); entityBuilder2.set("propertyName", "value2"); FullEntity entity2 = entityBuilder2.build(); transaction.addWithDeferredIdAllocation(entity1, entity2); Response response = transaction.commit(); // [END multipleAddEntitiesDeferredId] return response.getGeneratedKeys(); }
Example #3
Source File: TwoStepsConversions.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
private EntityValue applyEntityValueBuilder(Object val, String kindName, Consumer<Builder> consumer, boolean createKey) { FullEntity.Builder<IncompleteKey> builder; if (!createKey) { builder = FullEntity.newBuilder(); } else { /* The following does 3 sequential null checks. We only want an ID value if the object isn't null, has an ID property, and the ID property isn't null. * */ Optional idProp = Optional.ofNullable(val) .map(v -> this.datastoreMappingContext.getPersistentEntity(v.getClass())) .map(datastorePersistentEntity -> datastorePersistentEntity.getIdProperty()) .map(id -> this.datastoreMappingContext.getPersistentEntity(val.getClass()) .getPropertyAccessor(val).getProperty(id)); IncompleteKey key = idProp.isPresent() ? this.objectToKeyFactory.getKeyFromId(idProp.get(), kindName) : this.objectToKeyFactory.getIncompleteKey(kindName); builder = FullEntity.newBuilder(key); } consumer.accept(builder); return EntityValue.of(builder.build()); }
Example #4
Source File: DefaultDatastoreEntityConverter.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
private Value setExcludeFromIndexes(Value convertedVal) { // ListValues must have its contents individually excluded instead. // the entire list must NOT be excluded or there will be an exception. // Same for maps and embedded entities which are stored as EntityValue. if (convertedVal.getClass().equals(EntityValue.class)) { FullEntity.Builder<IncompleteKey> builder = FullEntity.newBuilder(); ((EntityValue) convertedVal).get().getProperties() .forEach((key, value) -> builder.set(key, setExcludeFromIndexes(value))); return EntityValue.of(builder.build()); } else if (convertedVal.getClass().equals(ListValue.class)) { return ListValue.of((List) ((ListValue) convertedVal).get().stream() .map(this::setExcludeFromIndexes).collect(Collectors.toList())); } else { return convertedVal.toBuilder().setExcludeFromIndexes(true).build(); } }
Example #5
Source File: DatastoreExample.java From google-cloud-java with Apache License 2.0 | 6 votes |
@Override public void run(Transaction tx, Key userKey, Contact contact) { Entity user = tx.get(userKey); if (user == null) { System.out.println("Adding a new user."); user = Entity.newBuilder(userKey).set("count", 0L).build(); tx.add(user); } FullEntity<IncompleteKey> contactEntity = FullEntity.newBuilder() .set("email", contact.email()) .set("phone", contact.phone()) .build(); tx.update(Entity.newBuilder(user).set("contact", contactEntity).build()); System.out.printf("Setting contact for user '%s'.%n", userKey.getName()); }
Example #6
Source File: DatastoreExample.java From google-cloud-java with Apache License 2.0 | 6 votes |
@Override public void run(Transaction tx, Key userKey, String content) { Entity user = tx.get(userKey); if (user == null) { System.out.println("Adding a new user."); user = Entity.newBuilder(userKey).set("count", 1).build(); tx.add(user); } else { user = Entity.newBuilder(user).set("count", user.getLong("count") + 1L).build(); tx.update(user); } IncompleteKey commentKey = IncompleteKey.newBuilder(userKey, COMMENT_KIND).build(); FullEntity<IncompleteKey> comment = FullEntity.newBuilder(commentKey) .set("content", content) .set("timestamp", Timestamp.now()) .build(); tx.addWithDeferredIdAllocation(comment); System.out.printf("Adding a comment to user '%s'.%n", userKey.getName()); }
Example #7
Source File: ConceptsTest.java From java-docs-samples with Apache License 2.0 | 6 votes |
@Test public void testBatchUpsert() { // [START datastore_batch_upsert] FullEntity<IncompleteKey> task1 = FullEntity.newBuilder(keyFactory.newKey()) .set("category", "Personal") .set("done", false) .set("priority", 4) .set("description", "Learn Cloud Datastore") .build(); FullEntity<IncompleteKey> task2 = Entity.newBuilder(keyFactory.newKey()) .set("category", "Personal") .set("done", false) .set("priority", 5) .set("description", "Integrate Cloud Datastore") .build(); List<Entity> tasks = datastore.add(task1, task2); Key taskKey1 = tasks.get(0).getKey(); Key taskKey2 = tasks.get(1).getKey(); // [END datastore_batch_upsert] assertEquals(Entity.newBuilder(taskKey1, task1).build(), datastore.get(taskKey1)); assertEquals(Entity.newBuilder(taskKey2, task2).build(), datastore.get(taskKey2)); }
Example #8
Source File: DefaultEntityManager.java From catatumbo with Apache License 2.0 | 6 votes |
/** * Returns an IncompleteKey of the given entity. * * @param entity * the entity * @return the incomplete key */ private IncompleteKey getIncompleteKey(Object entity) { EntityMetadata entityMetadata = EntityIntrospector.introspect(entity.getClass()); String kind = entityMetadata.getKind(); ParentKeyMetadata parentKeyMetadata = entityMetadata.getParentKeyMetadata(); DatastoreKey parentKey = null; IncompleteKey incompleteKey = null; if (parentKeyMetadata != null) { parentKey = (DatastoreKey) IntrospectionUtils.getFieldValue(parentKeyMetadata, entity); } if (parentKey != null) { incompleteKey = IncompleteKey.newBuilder(parentKey.nativeKey(), kind).build(); } else { incompleteKey = IncompleteKey.newBuilder(datastore.getOptions().getProjectId(), kind) .setNamespace(getEffectiveNamespace()).build(); } return incompleteKey; }
Example #9
Source File: MarshallerTest.java From catatumbo with Apache License 2.0 | 5 votes |
@Test public void testMarshal_WrappedLongObjectId3() { WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample3(); FullEntity<?> nativeEntity = (FullEntity<?>) Marshaller.marshal(em, entity, Intent.INSERT); IncompleteKey incompleteKey = nativeEntity.getKey(); assertNotNull(incompleteKey); }
Example #10
Source File: DatastoreSnippets.java From google-cloud-java with Apache License 2.0 | 5 votes |
/** Example of allocating multiple ids in a single batch. */ // [TARGET allocateId(IncompleteKey...)] public List<Key> batchAllocateId() { // [START batchAllocateId] 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); // [END batchAllocateId] return keys; }
Example #11
Source File: DatastoreSnippets.java From google-cloud-java with Apache License 2.0 | 5 votes |
/** Example of allocating an id. */ // [TARGET allocateId(IncompleteKey)] public Key allocateIdSingle() { // [START allocateIdSingle] KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); IncompleteKey incompleteKey = keyFactory.newKey(); // let cloud datastore automatically assign an id Key key = datastore.allocateId(incompleteKey); // [END allocateIdSingle] return key; }
Example #12
Source File: DatastoreDao.java From getting-started-java with Apache License 2.0 | 5 votes |
@Override public Long createBook(Book book) { IncompleteKey key = keyFactory.newKey(); // Key will be assigned once written FullEntity<IncompleteKey> incBookEntity = Entity.newBuilder(key) // Create the Entity .set(Book.AUTHOR, book.getAuthor()) // Add Property ("author", book.getAuthor()) .set(Book.DESCRIPTION, book.getDescription()) .set(Book.PUBLISHED_DATE, book.getPublishedDate()) .set(Book.TITLE, book.getTitle()) .set(Book.IMAGE_URL, book.getImageUrl()) .set(Book.CREATED_BY, book.getCreatedBy()) .set(Book.CREATED_BY_ID, book.getCreatedById()) .build(); Entity bookEntity = datastore.add(incBookEntity); // Save the Entity return bookEntity.getKey().getId(); // The ID of the Key }
Example #13
Source File: DatastoreDao.java From getting-started-java with Apache License 2.0 | 5 votes |
@Override public Long createBook(Book book) { IncompleteKey key = keyFactory.newKey(); // Key will be assigned once written FullEntity<IncompleteKey> incBookEntity = Entity.newBuilder(key) // Create the Entity .set(Book.AUTHOR, book.getAuthor()) // Add Property ("author", book.getAuthor()) .set(Book.DESCRIPTION, book.getDescription()) .set(Book.PUBLISHED_DATE, book.getPublishedDate()) .set(Book.TITLE, book.getTitle()) .set(Book.IMAGE_URL, book.getImageUrl()) .build(); Entity bookEntity = datastore.add(incBookEntity); // Save the Entity return bookEntity.getKey().getId(); // The ID of the Key }
Example #14
Source File: DatastoreDao.java From getting-started-java with Apache License 2.0 | 5 votes |
@Override public Long createBook(Book book) { IncompleteKey key = keyFactory.newKey(); // Key will be assigned once written FullEntity<IncompleteKey> incBookEntity = Entity.newBuilder(key) // Create the Entity .set(Book.AUTHOR, book.getAuthor()) // Add Property ("author", book.getAuthor()) .set(Book.DESCRIPTION, book.getDescription()) .set(Book.PUBLISHED_DATE, book.getPublishedDate()) .set(Book.TITLE, book.getTitle()) .build(); Entity bookEntity = datastore.add(incBookEntity); // Save the Entity return bookEntity.getKey().getId(); // The ID of the Key }
Example #15
Source File: DatastoreDao.java From getting-started-java with Apache License 2.0 | 5 votes |
@Override public Long createBook(Book book) { IncompleteKey key = keyFactory.newKey(); // Key will be assigned once written FullEntity<IncompleteKey> incBookEntity = Entity.newBuilder(key) // Create the Entity .set(Book.AUTHOR, book.getAuthor()) // Add Property ("author", book.getAuthor()) .set(Book.DESCRIPTION, book.getDescription()) .set(Book.PUBLISHED_DATE, book.getPublishedDate()) .set(Book.TITLE, book.getTitle()) .set(Book.IMAGE_URL, book.getImageUrl()) .set(Book.CREATED_BY, book.getCreatedBy()) .set(Book.CREATED_BY_ID, book.getCreatedById()) .build(); Entity bookEntity = datastore.add(incBookEntity); // Save the Entity return bookEntity.getKey().getId(); // The ID of the Key }
Example #16
Source File: DatastoreTemplate.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
private <T> List<T> convertEntitiesForRead(Iterator<? extends BaseEntity> entities, Class<T> entityClass, ReadContext context) { if (entities == null) { return Collections.emptyList(); } List<BaseKey> keys = new ArrayList<>(); entities.forEachRemaining(e -> { IncompleteKey key = e.getKey(); context.putReadEntity(key, e); keys.add(key); }); return convertEntitiesForRead(keys, entityClass, context); }
Example #17
Source File: MarshallerTest.java From catatumbo with Apache License 2.0 | 5 votes |
@Test public void testMarshal_WrappedLongObjectId1() { WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample1(); FullEntity<?> nativeEntity = (FullEntity<?>) Marshaller.marshal(em, entity, Intent.INSERT); IncompleteKey incompleteKey = nativeEntity.getKey(); assertNotNull(incompleteKey); }
Example #18
Source File: MarshallerTest.java From catatumbo with Apache License 2.0 | 5 votes |
@Test public void testMarshal_WrappedLongObjectId2() { WrappedLongObjectIdEntity entity = WrappedLongObjectIdEntity.getSample2(); FullEntity<?> nativeEntity = (FullEntity<?>) Marshaller.marshal(em, entity, Intent.INSERT); IncompleteKey incompleteKey = nativeEntity.getKey(); assertNotNull(incompleteKey); }
Example #19
Source File: DatastoreServiceObjectToKeyFactoryTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void allocateIdForObjectTest() { TestEntityWithKeyId testEntityWithKeyId = new TestEntityWithKeyId(); doAnswer((invocation) -> { IncompleteKey incompleteKey = (IncompleteKey) invocation.getArguments()[0]; long id = 123L; if (incompleteKey.getAncestors().size() > 0) { id = 456L; } return Key.newBuilder(incompleteKey, id).build(); }).when(this.datastore).allocateId((IncompleteKey) any()); when(this.datastore.newKeyFactory()).thenReturn(new KeyFactory("project")); Key allocatedKey = this.datastoreServiceObjectToKeyFactory .allocateKeyForObject(testEntityWithKeyId, this.datastoreMappingContext .getPersistentEntity(testEntityWithKeyId.getClass())); Key key = new KeyFactory("project").setKind("custom_test_kind").newKey(123L); assertThat(allocatedKey).isEqualTo(key); assertThat(testEntityWithKeyId.id).isEqualTo(key); Key allocatedKeyWithAncestor = this.datastoreServiceObjectToKeyFactory .allocateKeyForObject(testEntityWithKeyId, this.datastoreMappingContext .getPersistentEntity(testEntityWithKeyId.getClass()), allocatedKey); Key keyWithAncestor = new KeyFactory("project").setKind("custom_test_kind") .addAncestor(PathElement.of(key.getKind(), key.getId())) .newKey(456L); assertThat(allocatedKeyWithAncestor).isEqualTo(keyWithAncestor); assertThat(testEntityWithKeyId.id).isEqualTo(keyWithAncestor); }
Example #20
Source File: MarshallerTest.java From catatumbo with Apache License 2.0 | 5 votes |
@Test public void testMarshal_WrappedLongId2() { WrappedLongIdEntity entity = WrappedLongIdEntity.getSample2(); FullEntity<?> nativeEntity = (FullEntity<?>) Marshaller.marshal(em, entity, Intent.INSERT); IncompleteKey incompleteKey = nativeEntity.getKey(); assertNotNull(incompleteKey); }
Example #21
Source File: MarshallerTest.java From catatumbo with Apache License 2.0 | 5 votes |
@Test public void testMarshal_WrappedLongId1() { WrappedLongIdEntity entity = WrappedLongIdEntity.getSample1(); FullEntity<?> nativeEntity = (FullEntity<?>) Marshaller.marshal(em, entity, Intent.INSERT); IncompleteKey incompleteKey = nativeEntity.getKey(); assertNotNull(incompleteKey); }
Example #22
Source File: Marshaller.java From catatumbo with Apache License 2.0 | 5 votes |
/** * Marshals the embedded field represented by the given metadata. * * @param embeddedMetadata * the metadata of the embedded field. * @param target * the object in which the embedded field is defined/accessible from. * @return the ValueBuilder equivalent to embedded object */ private ValueBuilder<?, ?, ?> marshalWithImplodedStrategy(EmbeddedMetadata embeddedMetadata, Object target) { try { Object embeddedObject = embeddedMetadata.getReadMethod().invoke(target); if (embeddedObject == null) { if (embeddedMetadata.isOptional()) { return null; } NullValue.Builder nullValueBuilder = NullValue.newBuilder(); nullValueBuilder.setExcludeFromIndexes(!embeddedMetadata.isIndexed()); return nullValueBuilder; } FullEntity.Builder<IncompleteKey> embeddedEntityBuilder = FullEntity.newBuilder(); for (PropertyMetadata propertyMetadata : embeddedMetadata.getPropertyMetadataCollection()) { marshalField(propertyMetadata, embeddedObject, embeddedEntityBuilder); } for (EmbeddedMetadata embeddedMetadata2 : embeddedMetadata.getEmbeddedMetadataCollection()) { ValueBuilder<?, ?, ?> embeddedEntityBuilder2 = marshalWithImplodedStrategy( embeddedMetadata2, embeddedObject); if (embeddedEntityBuilder2 != null) { embeddedEntityBuilder.set(embeddedMetadata2.getMappedName(), embeddedEntityBuilder2.build()); } } EntityValue.Builder valueBuilder = EntityValue.newBuilder(embeddedEntityBuilder.build()); valueBuilder.setExcludeFromIndexes(!embeddedMetadata.isIndexed()); return valueBuilder; } catch (Throwable t) { throw new EntityManagerException(t); } }
Example #23
Source File: Marshaller.java From catatumbo with Apache License 2.0 | 5 votes |
/** * Creates an IncompleteKey. * * @param parent * the parent key, may be <code>null</code>. */ private void createIncompleteKey(Key parent) { String kind = entityMetadata.getKind(); if (parent == null) { key = entityManager.newNativeKeyFactory().setKind(kind).newKey(); } else { key = IncompleteKey.newBuilder(parent, kind).build(); } }
Example #24
Source File: MapMapper.java From catatumbo with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public ValueBuilder<?, ?, ?> toDatastore(Object input) { if (input == null) { return NullValue.newBuilder(); } Map<String, ?> map = (Map<String, ?>) input; FullEntity.Builder<IncompleteKey> entityBuilder = FullEntity.newBuilder(); for (Map.Entry<String, ?> entry : map.entrySet()) { String key = entry.getKey(); entityBuilder.set(key, valueMapper.toDatastore(entry.getValue()).build()); } return EntityValue.newBuilder(entityBuilder.build()); }
Example #25
Source File: CatchAllMapper.java From catatumbo with Apache License 2.0 | 5 votes |
@Override public ValueBuilder<?, ?, ?> toDatastore(Object input) { ValueBuilder<?, ?, ?> builder; if (input == null) { builder = NullValue.newBuilder(); } else if (input instanceof Long) { builder = LongValue.newBuilder((long) input); } else if (input instanceof Double) { builder = DoubleValue.newBuilder((double) input); } else if (input instanceof Boolean) { builder = BooleanValue.newBuilder((boolean) input); } else if (input instanceof String) { builder = StringValue.newBuilder((String) input); } else if (input instanceof DatastoreKey) { builder = KeyValue.newBuilder(((DatastoreKey) input).nativeKey()); } else if (input instanceof GeoLocation) { GeoLocation geoLocation = (GeoLocation) input; builder = LatLngValue .newBuilder(LatLng.of(geoLocation.getLatitude(), geoLocation.getLongitude())); } else if (input instanceof Map) { @SuppressWarnings("unchecked") Map<String, ?> map = (Map<String, ?>) input; FullEntity.Builder<IncompleteKey> entityBuilder = FullEntity.newBuilder(); for (Map.Entry<String, ?> entry : map.entrySet()) { String key = entry.getKey(); entityBuilder.set(key, toDatastore(entry.getValue()).build()); } builder = EntityValue.newBuilder(entityBuilder.build()); } else { throw new MappingException(String.format("Unsupported type: %s", input.getClass().getName())); } return builder; }
Example #26
Source File: EmbeddedObjectMapper.java From catatumbo with Apache License 2.0 | 5 votes |
@Override public ValueBuilder<?, ?, ?> toDatastore(Object input) { if (input == null) { return NullValue.newBuilder(); } try { FullEntity.Builder<IncompleteKey> entityBuilder = FullEntity.newBuilder(); for (PropertyMetadata propertyMetadata : metadata.getPropertyMetadataCollection()) { Object propertyValue = propertyMetadata.getReadMethod().invoke(input); if (propertyValue == null && propertyMetadata.isOptional()) { continue; } ValueBuilder<?, ?, ?> valueBuilder = propertyMetadata.getMapper() .toDatastore(propertyValue); // ListValues cannot have indexing turned off. Indexing is turned on by // default, so we don't touch excludeFromIndexes for ListValues. if (valueBuilder.getValueType() != ValueType.LIST) { valueBuilder.setExcludeFromIndexes(!propertyMetadata.isIndexed()); } Value<?> value = valueBuilder.build(); entityBuilder.set(propertyMetadata.getMappedName(), value); Indexer indexer = propertyMetadata.getSecondaryIndexer(); if (indexer != null) { entityBuilder.set(propertyMetadata.getSecondaryIndexName(), indexer.index(value)); } } return EntityValue.newBuilder(entityBuilder.build()); } catch (Throwable exp) { throw new MappingException(exp); } }
Example #27
Source File: DatastoreTemplate.java From spring-cloud-gcp with Apache License 2.0 | 4 votes |
private <T> StructuredQuery exampleToQuery(Example<T> example, DatastoreQueryOptions queryOptions, boolean keyQuery) { validateExample(example); T probe = example.getProbe(); FullEntity.Builder<IncompleteKey> probeEntityBuilder = Entity.newBuilder(); this.datastoreEntityConverter.write(probe, probeEntityBuilder); FullEntity<IncompleteKey> probeEntity = probeEntityBuilder.build(); DatastorePersistentEntity<?> persistentEntity = this.datastoreMappingContext.getPersistentEntity(example.getProbeType()); StructuredQuery.Builder builder = keyQuery ? Query.newKeyQueryBuilder() : Query.newEntityQueryBuilder(); builder.setKind(persistentEntity.kindName()); ExampleMatcherAccessor matcherAccessor = new ExampleMatcherAccessor(example.getMatcher()); matcherAccessor.getPropertySpecifiers(); LinkedList<StructuredQuery.Filter> filters = new LinkedList<>(); persistentEntity.doWithColumnBackedProperties((persistentProperty) -> { if (!example.getMatcher().isIgnoredPath(persistentProperty.getName())) { // ID properties are not stored as regular fields in Datastore. String fieldName = persistentProperty.getFieldName(); Value<?> value; if (persistentProperty.isIdProperty()) { PersistentPropertyAccessor accessor = persistentEntity.getPropertyAccessor(probe); value = KeyValue.of( createKey(persistentEntity.kindName(), accessor.getProperty(persistentProperty))); } else { value = probeEntity.getValue(fieldName); } if (value instanceof NullValue && example.getMatcher().getNullHandler() != ExampleMatcher.NullHandler.INCLUDE) { //skip null value return; } filters.add(StructuredQuery.PropertyFilter.eq(fieldName, value)); } }); if (!filters.isEmpty()) { builder.setFilter( StructuredQuery.CompositeFilter.and(filters.pop(), filters.toArray(new StructuredQuery.Filter[0]))); } applyQueryOptions(builder, queryOptions, persistentEntity); return builder.build(); }
Example #28
Source File: DatastoreServiceObjectToKeyFactory.java From spring-cloud-gcp with Apache License 2.0 | 4 votes |
@Override public IncompleteKey getIncompleteKey(String kindName) { return this.datastore.get().newKeyFactory().setKind(kindName).newKey(); }
Example #29
Source File: DatastoreExample.java From google-cloud-java with Apache License 2.0 | 4 votes |
@Override public void run(Transaction tx, Key userKey, Void arg) { Entity user = tx.get(userKey); if (user == null) { System.out.printf("User '%s' does not exist.%n", userKey.getName()); return; } 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<>(); StructuredQuery<Entity> query = Query.newEntityQueryBuilder() .setNamespace(NAMESPACE) .setKind(COMMENT_KIND) .setFilter(PropertyFilter.hasAncestor(userKey)) .setLimit(limit) .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++; } if (resultCount < limit) { break; } query = query.toBuilder().setStartCursor(results.getCursorAfter()).build(); } // We could have added "ORDER BY timestamp" to the query to avoid sorting, but that would // require adding an ancestor index for timestamp. // See: https://cloud.google.com/datastore/docs/tools/indexconfig for (Map.Entry<Timestamp, String> entry : sortedComments.entrySet()) { System.out.printf("\t%s: %s%n", entry.getKey(), entry.getValue()); } }
Example #30
Source File: Greeting.java From java-docs-samples with Apache License 2.0 | 4 votes |
private IncompleteKey makeIncompleteKey() { // The book is our ancestor key. return Key.newBuilder(book.getKey(), "Greeting").build(); }