com.google.cloud.datastore.Query类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(14.5k)|赞(0)|评价(0)|浏览(161)

本文整理了Java中com.google.cloud.datastore.Query类的一些代码示例,展示了Query类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Query类的具体详情如下:
包路径:com.google.cloud.datastore.Query
类名称:Query

Query介绍

[英]A Google Cloud Datastore query. For usage examples see GqlQuery and StructuredQuery.

Note that queries require proper indexing. See Cloud Datastore Index Configuration for help configuring indexes.
[中]谷歌云数据存储查询。有关用法示例,请参见GqlQuery和StructuredQuery。
请注意,查询需要适当的索引。有关配置索引的帮助,请参阅Cloud Datastore Index Configuration

代码示例

代码示例来源:origin: googleapis/google-cloud-java

Entity johnEntity = datastore.get(key);
  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)
  Query.newEntityQueryBuilder()
    .setKind("Person")
    .setFilter(PropertyFilter.eq("favorite_food", "pizza"))
    .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!");

代码示例来源:origin: googleapis/google-cloud-java

@Test
public void testGqlQueryPagination() throws DatastoreException {
 List<RunQueryResponse> responses = buildResponsesForQueryPagination();
 for (int i = 0; i < responses.size(); i++) {
  EasyMock.expect(rpcMock.runQuery(EasyMock.anyObject(RunQueryRequest.class)))
    .andReturn(responses.get(i));
 }
 EasyMock.replay(rpcFactoryMock, rpcMock);
 Datastore mockDatastore = rpcMockOptions.getService();
 QueryResults<Key> results =
   mockDatastore.run(
     Query.newGqlQueryBuilder(ResultType.KEY, "select __key__ from *").build());
 int count = 0;
 while (results.hasNext()) {
  count += 1;
  results.next();
 }
 assertEquals(count, 5);
 EasyMock.verify(rpcFactoryMock, rpcMock);
}

代码示例来源:origin: googleapis/google-cloud-java

/** Deletes all entities in the namespace associated with this {@link RemoteDatastoreHelper}. */
public void deleteNamespace() {
 StructuredQuery<Key> query = Query.newKeyQueryBuilder().setNamespace(namespace).build();
 QueryResults<Key> keys = datastore.run(query);
 while (keys.hasNext()) {
  datastore.delete(keys.next());
 }
}

代码示例来源:origin: googleapis/google-cloud-java

QueryResultsImpl(
  DatastoreImpl datastore, com.google.datastore.v1.ReadOptions readOptionsPb, Query<T> query) {
 this.datastore = datastore;
 this.readOptionsPb = readOptionsPb;
 this.query = query;
 queryResultType = query.getType();
 com.google.datastore.v1.PartitionId.Builder pbBuilder =
   com.google.datastore.v1.PartitionId.newBuilder();
 pbBuilder.setProjectId(datastore.getOptions().getProjectId());
 if (query.getNamespace() != null) {
  pbBuilder.setNamespaceId(query.getNamespace());
 } else if (datastore.getOptions().getNamespace() != null) {
  pbBuilder.setNamespaceId(datastore.getOptions().getNamespace());
 }
 partitionIdPb = pbBuilder.build();
 sendRequest();
 if (runQueryResponsePb.getBatch().getSkippedResults() > 0) {
  cursor = runQueryResponsePb.getBatch().getSkippedCursor();
 } else {
  cursor = mostRecentQueryPb.getStartCursor();
 }
}

代码示例来源:origin: googleapis/google-cloud-java

@Test
public void testTransactionWithQuery() throws InterruptedException {
 Query<Entity> query =
   Query.newEntityQueryBuilder()
     .setKind(KIND2)
     .setFilter(PropertyFilter.hasAncestor(KEY2))
     .setNamespace(NAMESPACE)
     .build();
 Transaction transaction = DATASTORE.newTransaction();
 QueryResults<Entity> results = transaction.run(query);
 assertTrue(results.hasNext());
 assertEquals(ENTITY2, results.next());
 assertFalse(results.hasNext());
 transaction.add(ENTITY3);
 transaction.commit();
 assertEquals(ENTITY3, DATASTORE.get(KEY3));
 transaction = DATASTORE.newTransaction();
 results = transaction.run(query);
 assertTrue(results.hasNext());
 assertEquals(ENTITY2, results.next());
 assertFalse(results.hasNext());
 transaction.delete(ENTITY3.getKey());
 DATASTORE.put(Entity.newBuilder(ENTITY2).clear().build());
 try {
  transaction.commit();

代码示例来源:origin: googleapis/google-cloud-java

/** 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;
}

代码示例来源:origin: googleapis/google-cloud-java

return;
if (user.contains("contact")) {
 FullEntity<IncompleteKey> contact = user.getEntity("contact");
 String email = contact.getString("email");
 String phone = contact.getString("phone");
   "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();
  break;
 query = query.toBuilder().setStartCursor(results.getCursorAfter()).build();

代码示例来源:origin: googleapis/google-cloud-java

@Test
public void testRunStructuredQuery() {
 Query<Entity> query =
   Query.newEntityQueryBuilder().setKind(KIND1).setOrderBy(OrderBy.asc("__key__")).build();
 QueryResults<Entity> results1 = datastore.run(query);
 assertTrue(results1.hasNext());
 assertEquals(ENTITY1, results1.next());
 assertFalse(results1.hasNext());
 Query<Key> keyOnlyQuery = Query.newKeyQueryBuilder().setKind(KIND1).build();
 QueryResults<Key> results2 = datastore.run(keyOnlyQuery);
 assertTrue(results2.hasNext());
 assertEquals(ENTITY1.getKey(), results2.next());
   Query.newProjectionEntityQueryBuilder().setKind(KIND1).setProjection("__key__").build();
 QueryResults<ProjectionEntity> results3 = datastore.run(keyOnlyProjectionQuery);
 assertEquals(ENTITY1.getKey(), projectionEntity.getKey());
   Query.newProjectionEntityQueryBuilder()
     .setKind(KIND2)
     .setProjection("age")
     .setFilter(PropertyFilter.gt("age", 18))
     .setDistinctOn("age")
     .setOrderBy(OrderBy.asc("age"))
 assertEquals(ENTITY2.getKey(), entity.getKey());
 assertEquals(20, entity.getLong("age"));
 assertEquals(1, entity.getProperties().size());

代码示例来源:origin: org.eclipse.jetty.gcloud/jetty-gcloud-session-manager

Query<Entity> query = Query.newEntityQueryBuilder()
    .setKind(_model.getKind())
    .setFilter(CompositeFilter.and(PropertyFilter.gt(_model.getExpiry(), 0), PropertyFilter.le(_model.getExpiry(), System.currentTimeMillis())))
    .setLimit(_maxResults)
    .build();
  results = _datastore.run(query);
  LOG.debug("Expiry query no index in {}ms", System.currentTimeMillis()-start);
  results = _datastore.run(query);
while (results.hasNext())
  Entity entity = results.next();
  info.add(new ExpiryInfo(entity.getString(_model.getId()),entity.getString(_model.getLastNode()), entity.getLong(_model.getExpiry())));

代码示例来源:origin: googleapis/google-cloud-java

/** Example of running a query to find all entities with an ancestor. */
// [TARGET run(Query)]
// [VARIABLE "my_parent_key_name"]
public List<Entity> run(String parentKeyName) {
 Datastore datastore = transaction.getDatastore();
 // [START run]
 KeyFactory keyFactory = datastore.newKeyFactory().setKind("ParentKind");
 Key parentKey = keyFactory.newKey(parentKeyName);
 // Build a query
 Query<Entity> query =
   Query.newEntityQueryBuilder()
     .setKind("MyKind")
     .setFilter(PropertyFilter.hasAncestor(parentKey))
     .build();
 QueryResults<Entity> results = transaction.run(query);
 List<Entity> entities = Lists.newArrayList();
 while (results.hasNext()) {
  Entity result = results.next();
  // do something with result
  entities.add(result);
 }
 transaction.commit();
 // [END run]
 return entities;
}

代码示例来源:origin: spotify/styx

public List<Workflow> workflows(String componentId) throws IOException {
 final Key componentKey = componentKey(datastore.newKeyFactory(), componentId);
 final List<Workflow> workflows = Lists.newArrayList();
 final EntityQuery query = Query.newEntityQueryBuilder()
   .setKind(KIND_WORKFLOW)
   .setFilter(PropertyFilter.hasAncestor(componentKey))
   .build();
 datastore.query(query, entity -> {
  final Workflow workflow;
  if (entity.contains(PROPERTY_WORKFLOW_JSON)) {
   try {
    workflow = OBJECT_MAPPER.readValue(entity.getString(PROPERTY_WORKFLOW_JSON), Workflow.class);
   } catch (IOException e) {
    LOG.warn("Failed to read workflow {}.", entity.getKey(), e);
    return;
   }
   workflows.add(workflow);
  }
 });
 return workflows;
}

代码示例来源:origin: org.eclipse.jetty.gcloud/jetty-gcloud-session-manager

Query<ProjectionEntity> query = Query.newProjectionEntityQueryBuilder()
    .setKind(_model.getKind())
    .setProjection(_model.getExpiry())
    .setFilter(CompositeFilter.and(PropertyFilter.eq(_model.getId(), id), 
                    PropertyFilter.eq(_model.getContextPath(), _context.getCanonicalContextPath()),
                    PropertyFilter.eq(_model.getVhost(), _context.getVhost())))
  presults = _datastore.run(query);
  LOG.debug("Exists query by index in {}ms", System.currentTimeMillis()-start);
  presults = _datastore.run(query);
if (presults.hasNext())
  ProjectionEntity pe = presults.next();
  return !isExpired(pe.getLong(_model.getExpiry()));
Query<Entity> query = Query.newEntityQueryBuilder()
    .setKind(_model.getKind())
    .setFilter(CompositeFilter.and(PropertyFilter.eq(_model.getId(), id), 
                    PropertyFilter.eq(_model.getContextPath(), _context.getCanonicalContextPath()),
                    PropertyFilter.eq(_model.getVhost(), _context.getVhost())))
    .build();
  results = _datastore.run(query);
if (results.hasNext())

代码示例来源:origin: org.eclipse.jetty.gcloud/jetty-gcloud-session-manager

Query<ProjectionEntity> query = Query.newProjectionEntityQueryBuilder()
    .setKind(_model.getKind())
    .setProjection(_model.getId(), _model.getLastNode(), _model.getExpiry())
    .setFilter(CompositeFilter.and(PropertyFilter.gt(_model.getExpiry(), 0), PropertyFilter.le(_model.getExpiry(), now)))
    .setLimit(_maxResults)
    .build();
  presults = _datastore.run(query);
  LOG.debug("Expiry query by index in {}ms", System.currentTimeMillis()-start);
  presults = _datastore.run(query);
while (presults.hasNext())
  ProjectionEntity pe = presults.next();
  info.add(new ExpiryInfo(pe.getString(_model.getId()),pe.getString(_model.getLastNode()), pe.getLong(_model.getExpiry())));

代码示例来源:origin: googleapis/google-cloud-java

@Before
public void setUp() {
 rpcFactoryMock = EasyMock.createStrictMock(DatastoreRpcFactory.class);
 rpcMock = EasyMock.createStrictMock(DatastoreRpc.class);
 rpcMockOptions =
   options
     .toBuilder()
     .setRetrySettings(ServiceOptions.getDefaultRetrySettings())
     .setServiceRpcFactory(rpcFactoryMock)
     .build();
 EasyMock.expect(rpcFactoryMock.create(rpcMockOptions)).andReturn(rpcMock);
 StructuredQuery<Key> query = Query.newKeyQueryBuilder().build();
 QueryResults<Key> result = datastore.run(query);
 datastore.delete(Iterators.toArray(result, Key.class));
 datastore.add(ENTITY1, ENTITY2);
}

代码示例来源:origin: googleapis/google-cloud-java

@Override
public void run(Transaction tx, Key userKey, Void arg) {
 Entity user = tx.get(userKey);
 if (user == null) {
  System.out.println("Nothing to delete, user does not exist.");
  return;
 }
 Query<Key> query =
   Query.newKeyQueryBuilder()
     .setNamespace(NAMESPACE)
     .setKind(COMMENT_KIND)
     .setFilter(PropertyFilter.hasAncestor(userKey))
     .build();
 QueryResults<Key> comments = tx.run(query);
 int count = 0;
 while (comments.hasNext()) {
  tx.delete(comments.next());
  count++;
 }
 tx.delete(userKey);
 System.out.printf("Deleting user '%s' and %d comment[s].%n", userKey.getName(), count);
}

代码示例来源:origin: googleapis/google-cloud-java

@Test
public void testRunGqlQueryNoCasting() throws InterruptedException {
 Query<Entity> query1 =
   Query.newGqlQueryBuilder(ResultType.ENTITY, "select * from " + KIND1)
     .setNamespace(NAMESPACE)
     .build();
 Query<Entity> scQuery1 =
   Query.newEntityQueryBuilder()
     .setNamespace(NAMESPACE)
     .setKind(KIND1)
     .setFilter(PropertyFilter.hasAncestor(ROOT_KEY))
 DATASTORE.put(ENTITY3);
 Query<? extends Entity> query2 =
   Query.newGqlQueryBuilder(ResultType.ENTITY, "select * from " + KIND2 + " order by __key__")
     .setNamespace(NAMESPACE)
     .build();
 Query<? extends Entity> scQuery2 =
   Query.newEntityQueryBuilder()
   Query.newGqlQueryBuilder(ResultType.ENTITY, "select * from bla")
     .setNamespace(NAMESPACE)
     .build();
 scQuery1 =
   Query.newEntityQueryBuilder()
     .setNamespace(NAMESPACE)
     .setFilter(PropertyFilter.hasAncestor(ROOT_KEY))
   Query.newGqlQueryBuilder(ResultType.KEY, "select __key__ from " + KIND1)
     .setNamespace(NAMESPACE)

代码示例来源:origin: googleapis/google-cloud-java

Query<Entity> query1 =
  (Query<Entity>)
    Query.newGqlQueryBuilder("select * from " + KIND1).setNamespace(NAMESPACE).build();
Query<Entity> scQuery1 =
  Query.newEntityQueryBuilder()
    .setNamespace(NAMESPACE)
    .setKind(KIND1)
    .setFilter(PropertyFilter.hasAncestor(ROOT_KEY))
    .build();
Iterator<Entity> results1 = getStronglyConsistentResults(scQuery1, query1);
  Query.newGqlQueryBuilder("select * from " + KIND1).setNamespace(NAMESPACE).build();
QueryResults<?> results2 = DATASTORE.run(query2);
assertSame(Entity.class, results2.getResultClass());
  Query.newEntityQueryBuilder()
    .setNamespace(NAMESPACE)
    .setKind(KIND1)
    .setFilter(PropertyFilter.hasAncestor(ROOT_KEY))
    .build();

代码示例来源:origin: googleapis/google-cloud-java

/** Example of creating and running a GQL query. */
// [TARGET newGqlQueryBuilder(String)]
// [VARIABLE "my_kind"]
public QueryResults<?> newQuery(String kind) {
 // [START newQuery]
 String gqlQuery = "select * from " + kind;
 Query<?> query = Query.newGqlQueryBuilder(gqlQuery).build();
 QueryResults<?> results = datastore.run(query);
 // Use results
 // [END newQuery]
 return results;
}

代码示例来源:origin: googleapis/google-cloud-java

private List<RunQueryResponse> buildResponsesForQueryPaginationWithLimit() {
 Entity entity4 = Entity.newBuilder(KEY4).set("value", StringValue.of("value")).build();
 Entity entity5 = Entity.newBuilder(KEY5).set("value", "value").build();
 datastore.add(ENTITY3, entity4, entity5);
 DatastoreRpc datastoreRpc = datastore.getOptions().getDatastoreRpcV1();
 List<RunQueryResponse> responses = new ArrayList<>();
 Query<Entity> query = Query.newEntityQueryBuilder().build();
 RunQueryRequest.Builder requestPb = RunQueryRequest.newBuilder();
 query.populatePb(requestPb);
 QueryResultBatch queryResultBatchPb =
   RunQueryResponse.newBuilder()

代码示例来源:origin: org.eclipse.jetty.gcloud/jetty-gcloud-session-manager

Query<Key> q = Query.newKeyQueryBuilder()
    .setKind(_model.getKind())
    .setFilter(PropertyFilter.eq(_model.getId(), s))
    .build();
QueryResults<Key> res = _datastore.run(q);
if (!res.hasNext())

相关文章