Java Code Examples for com.google.cloud.datastore.QueryResults#hasNext()
The following examples show how to use
com.google.cloud.datastore.QueryResults#hasNext() .
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: ConceptsTest.java From java-docs-samples with Apache License 2.0 | 6 votes |
@Test public void testRunProjectionQuery() { setUpQueryTests(); Query<ProjectionEntity> query = Query.newProjectionEntityQueryBuilder() .setKind("Task") .setProjection("priority", "percent_complete") .build(); // [START datastore_run_query_projection] List<Long> priorities = new LinkedList<>(); List<Double> percentCompletes = new LinkedList<>(); QueryResults<ProjectionEntity> tasks = datastore.run(query); while (tasks.hasNext()) { ProjectionEntity task = tasks.next(); priorities.add(task.getLong("priority")); percentCompletes.add(task.getDouble("percent_complete")); } // [END datastore_run_query_projection] assertEquals(ImmutableList.of(4L), priorities); assertEquals(ImmutableList.of(10.0), percentCompletes); }
Example 2
Source File: DatastoreSessionFilter.java From getting-started-java with Apache License 2.0 | 6 votes |
@Override public void init(FilterConfig config) throws ServletException { // initialize local copy of datastore session variables datastore = DatastoreOptions.getDefaultInstance().getService(); keyFactory = datastore.newKeyFactory().setKind("SessionVariable"); // Delete all sessions unmodified for over two days DateTime dt = DateTime.now(DateTimeZone.UTC); Query<Entity> query = Query.newEntityQueryBuilder() .setKind("SessionVariable") .setFilter(PropertyFilter.le("lastModified", dt.minusDays(2).toString(dtf))) .build(); QueryResults<Entity> resultList = datastore.run(query); while (resultList.hasNext()) { Entity stateEntity = resultList.next(); datastore.delete(stateEntity.getKey()); } }
Example 3
Source File: DatastoreStatsTest.java From catatumbo with Apache License 2.0 | 6 votes |
@Test public void testGetKindNs_Namespace_KindName() { final String namespace = "junit"; final String kindName = "StringField"; StatKindNs statEntity = stats.getKindNs(namespace, kindName); Query query = Query.newEntityQueryBuilder().setNamespace(namespace) .setKind(StatConstants.STAT_KIND_NS) .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName)) .build(); QueryResults<com.google.cloud.datastore.Entity> results = datastore.run(query); com.google.cloud.datastore.Entity nativeEntity = null; if (results.hasNext()) { nativeEntity = results.next(); } assertTrue(equals(statEntity, nativeEntity)); }
Example 4
Source File: DatastoreSessionFilter.java From getting-started-java with Apache License 2.0 | 6 votes |
protected void deleteSessionWithValue(String varName, String varValue) { Transaction transaction = datastore.newTransaction(); try { Query<Entity> query = Query.newEntityQueryBuilder() .setKind("SessionVariable") .setFilter(PropertyFilter.eq(varName, varValue)) .build(); QueryResults<Entity> resultList = transaction.run(query); while (resultList.hasNext()) { Entity stateEntity = resultList.next(); transaction.delete(stateEntity.getKey()); } transaction.commit(); } finally { if (transaction.isActive()) { transaction.rollback(); } } }
Example 5
Source File: DatastoreSnippets.java From google-cloud-java with Apache License 2.0 | 6 votes |
/** Example of running a query to find all entities of one kind. */ // [TARGET run(Query, ReadOption...)] // [VARIABLE "my_kind"] public List<Entity> runQuery(String kind) { // TODO change so that it's not necessary to hold the entities in a list for integration testing // [START runQuery] 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); } // [END runQuery] return entities; }
Example 6
Source File: DatastoreSessionFilter.java From getting-started-java with Apache License 2.0 | 6 votes |
@Override public void init(FilterConfig config) throws ServletException { // initialize local copy of datastore session variables datastore = DatastoreOptions.getDefaultInstance().getService(); keyFactory = datastore.newKeyFactory().setKind("SessionVariable"); // Delete all sessions unmodified for over two days DateTime dt = DateTime.now(DateTimeZone.UTC); Query<Entity> query = Query.newEntityQueryBuilder() .setKind("SessionVariable") .setFilter(PropertyFilter.le("lastModified", dt.minusDays(2).toString(dtf))) .build(); QueryResults<Entity> resultList = datastore.run(query); while (resultList.hasNext()) { Entity stateEntity = resultList.next(); datastore.delete(stateEntity.getKey()); } }
Example 7
Source File: DatastoreSessionFilter.java From getting-started-java with Apache License 2.0 | 6 votes |
@Override public void init(FilterConfig config) throws ServletException { // initialize local copy of datastore session variables datastore = DatastoreOptions.getDefaultInstance().getService(); keyFactory = datastore.newKeyFactory().setKind("SessionVariable"); // Delete all sessions unmodified for over two days DateTime dt = DateTime.now(DateTimeZone.UTC); Query<Entity> query = Query.newEntityQueryBuilder() .setKind("SessionVariable") .setFilter(PropertyFilter.le("lastModified", dt.minusDays(2).toString(dtf))) .build(); QueryResults<Entity> resultList = datastore.run(query); while (resultList.hasNext()) { Entity stateEntity = resultList.next(); datastore.delete(stateEntity.getKey()); } }
Example 8
Source File: DatastoreSnippets.java From google-cloud-java with Apache License 2.0 | 6 votes |
/** Example of running a query to find all entities with a matching property value. */ // [TARGET run(Query, ReadOption...)] // [VARIABLE "my_kind"] // [VARIABLE "my_property"] // [VARIABLE "my_value"] public List<Entity> runQueryOnProperty(String kind, String property, String value) { // TODO change so that it's not necessary to hold the entities in a list for integration testing // [START runQueryOnProperty] 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); } // [END runQueryOnProperty] return entities; }
Example 9
Source File: ConceptsTest.java From java-docs-samples with Apache License 2.0 | 6 votes |
@Test public void testNamespaceRunQuery() { setUpQueryTests(); // [START datastore_namespace_run_query] KeyFactory keyFactory = datastore.newKeyFactory().setKind("__namespace__"); Key startNamespace = keyFactory.newKey("g"); Key endNamespace = keyFactory.newKey("h"); Query<Key> query = Query.newKeyQueryBuilder() .setKind("__namespace__") .setFilter(CompositeFilter.and( PropertyFilter.gt("__key__", startNamespace), PropertyFilter.lt("__key__", endNamespace))) .build(); List<String> namespaces = new ArrayList<>(); QueryResults<Key> results = datastore.run(query); while (results.hasNext()) { namespaces.add(results.next().getName()); } // [END datastore_namespace_run_query] assertEquals(ImmutableList.of("ghijklmnop"), namespaces); }
Example 10
Source File: GoogleJobStore.java From data-transfer-project with Apache License 2.0 | 6 votes |
/** * Finds the ID of the first {@link PortabilityJob} in state {@code jobState} in Datastore, or * null if none found. * * <p>TODO(rtannenbaum): Order by creation time so we can process jobs in a FIFO manner. Trying to * OrderBy.asc("created") currently fails because we don't yet have an index set up. */ @Override public UUID findFirst(JobAuthorization.State jobState) { Query<Key> query = Query.newKeyQueryBuilder() .setKind(JOB_KIND) .setFilter(PropertyFilter.eq(PortabilityJob.AUTHORIZATION_STATE, jobState.name())) // .setOrderBy(OrderBy.asc("created")) .setLimit(1) .build(); QueryResults<Key> results = datastore.run(query); if (!results.hasNext()) { return null; } Key key = results.next(); return UUID.fromString(key.getName()); }
Example 11
Source File: DefaultDatastoreReader.java From catatumbo with Apache License 2.0 | 5 votes |
/** * Executes the given {@link KeyQueryRequest} and returns the response. * * @param request * the key query request * @return the query response */ public QueryResponse<DatastoreKey> executeKeyQueryRequest(KeyQueryRequest request) { try { GqlQuery.Builder<Key> queryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, request.getQuery()); queryBuilder.setNamespace(entityManager.getEffectiveNamespace()); queryBuilder.setAllowLiteral(request.isAllowLiterals()); QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings()); QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings()); GqlQuery<Key> gqlQuery = queryBuilder.build(); QueryResults<Key> results = nativeReader.run(gqlQuery); List<DatastoreKey> entities = new ArrayList<>(); DefaultQueryResponse<DatastoreKey> response = new DefaultQueryResponse<>(); response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); while (results.hasNext()) { Key result = results.next(); DatastoreKey datastoreKey = new DefaultDatastoreKey(result); entities.add(datastoreKey); } response.setResults(entities); response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); response.setQueryResponseMetadata( new DefaultQueryResponseMetadata( QueryResponseMetadata.QueryState.forMoreResultsType(results.getMoreResults()))); return response; } catch (DatastoreException exp) { throw new EntityManagerException(exp); } }
Example 12
Source File: DatastoreStatsTest.java From catatumbo with Apache License 2.0 | 5 votes |
@Test public void testGetKind() { final String kindName = "StringField"; StatKind statEntity = stats.getKind(kindName); Query query = Query.newEntityQueryBuilder().setNamespace("").setKind(StatConstants.STAT_KIND) .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName)) .build(); QueryResults<com.google.cloud.datastore.Entity> results = datastore.run(query); com.google.cloud.datastore.Entity nativeEntity = null; if (results.hasNext()) { nativeEntity = results.next(); } assertTrue(equals(statEntity, nativeEntity)); }
Example 13
Source File: DatastoreStatsTest.java From catatumbo with Apache License 2.0 | 5 votes |
@Test public void testGetKindNs_KindName() { final String kindName = "StringField"; StatKindNs statEntity = stats.getKindNs(kindName); Query query = Query.newEntityQueryBuilder().setKind(StatConstants.STAT_KIND_NS) .setFilter(StructuredQuery.PropertyFilter.eq(StatConstants.PROP_KIND_NAME, kindName)) .build(); QueryResults<com.google.cloud.datastore.Entity> results = datastore.run(query); com.google.cloud.datastore.Entity nativeEntity = null; if (results.hasNext()) { nativeEntity = results.next(); } assertTrue(equals(statEntity, nativeEntity)); }
Example 14
Source File: DefaultDatastoreMetadata.java From catatumbo with Apache License 2.0 | 5 votes |
@Override public QueryResponse<String> getNamespaces(DatastoreCursor fromCursor, int limit) { try { String query = "SELECT __key__ FROM " + ENTITY_NAMESPACES + " ORDER BY __key__"; if (limit > 0) { query += " LIMIT @Limit"; } query += " OFFSET @Offset"; GqlQuery.Builder<Key> gqlQueryBuilder = Query.newGqlQueryBuilder(ResultType.KEY, query); if (limit > 0) { gqlQueryBuilder.setBinding("Limit", limit); } gqlQueryBuilder.setBinding("Offset", Cursor.fromUrlSafe(fromCursor.getEncoded())); GqlQuery<Key> gqlQuery = gqlQueryBuilder.build(); Datastore datastore = entityManager.getDatastore(); QueryResults<Key> results = datastore.run(gqlQuery); DefaultQueryResponse<String> response = new DefaultQueryResponse<>(); List<String> namespaces = new ArrayList<>(Math.max(limit, 50)); response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); while (results.hasNext()) { Key key = results.next(); String name = key.getName(); namespaces.add(name == null ? "" : name); } response.setResults(namespaces); response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe())); return response; } catch (DatastoreException exp) { throw new EntityManagerException(exp); } }
Example 15
Source File: DatastoreStatsTest.java From catatumbo with Apache License 2.0 | 5 votes |
@Test public void testGetCompositeIndexes() { List<StatCompositeIndex> statEntities = stats.getCompositeIndexes(); Query query = Query.newEntityQueryBuilder().setNamespace("") .setKind(StatConstants.STAT_COMPOSITE_INDEX).build(); QueryResults<com.google.cloud.datastore.Entity> results = datastore.run(query); int i = 0; while (results.hasNext()) { StatCompositeIndex statEntity = statEntities.get(i); com.google.cloud.datastore.Entity nativeEntity = results.next(); assertTrue(equals(statEntity, nativeEntity)); i++; } }
Example 16
Source File: MessageRepositoryImpl.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Override public List<Message> retrieve(int limit) { // Get Message saved in Datastore Datastore datastore = getDatastoreInstance(); Query<Entity> query = Query.newEntityQueryBuilder() .setKind(messagesKind) .setLimit(limit) .addOrderBy(StructuredQuery.OrderBy.desc("publishTime")) .build(); QueryResults<Entity> results = datastore.run(query); List<Message> messages = new ArrayList<>(); while (results.hasNext()) { Entity entity = results.next(); Message message = new Message(entity.getString("messageId")); String data = entity.getString("data"); if (data != null) { message.setData(data); } String publishTime = entity.getString("publishTime"); if (publishTime != null) { message.setPublishTime(publishTime); } messages.add(message); } return messages; }
Example 17
Source File: DatastoreDao.java From getting-started-java with Apache License 2.0 | 5 votes |
public List<Book> entitiesToBooks(QueryResults<Entity> resultList) { List<Book> resultBooks = new ArrayList<>(); while (resultList.hasNext()) { // We still have data resultBooks.add(entityToBook(resultList.next())); // Add the Book to the List } return resultBooks; }
Example 18
Source File: MessageRepositoryImpl.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Override public List<Message> retrieve(int limit) { // Get Message saved in Datastore Datastore datastore = getDatastoreInstance(); Query<Entity> query = Query.newEntityQueryBuilder() .setKind(messagesKind) .setLimit(limit) .addOrderBy(StructuredQuery.OrderBy.desc("publishTime")) .build(); QueryResults<Entity> results = datastore.run(query); List<Message> messages = new ArrayList<>(); while (results.hasNext()) { Entity entity = results.next(); Message message = new Message(entity.getString("messageId")); String data = entity.getString("data"); if (data != null) { message.setData(data); } String publishTime = entity.getString("publishTime"); if (publishTime != null) { message.setPublishTime(publishTime); } messages.add(message); } return messages; }
Example 19
Source File: MessageRepositoryImpl.java From java-docs-samples with Apache License 2.0 | 5 votes |
@Override public List<Message> retrieve(int limit) { // Get Message saved in Datastore Datastore datastore = getDatastoreInstance(); Query<Entity> query = Query.newEntityQueryBuilder() .setKind(messagesKind) .setLimit(limit) .addOrderBy(StructuredQuery.OrderBy.desc("publishTime")) .build(); QueryResults<Entity> results = datastore.run(query); List<Message> messages = new ArrayList<>(); while (results.hasNext()) { Entity entity = results.next(); Message message = new Message(entity.getString("messageId")); String data = entity.getString("data"); if (data != null) { message.setData(data); } String publishTime = entity.getString("publishTime"); if (publishTime != null) { message.setPublishTime(publishTime); } if (entity.contains("sourceLang")) { String sourceLang = entity.getString("sourceLang"); if (sourceLang != null) { message.setSourceLang(sourceLang); } } if (entity.contains("targetLang")) { String targetLang = entity.getString("targetLang"); if (targetLang != null) { message.setTargetLang(targetLang); } } messages.add(message); } return messages; }
Example 20
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()); } }