com.google.cloud.datastore.ProjectionEntity Java Examples

The following examples show how to use com.google.cloud.datastore.ProjectionEntity. 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: ShardedCounterMetricsStore.java    From nexus-blobstore-google-cloud with Eclipse Public License 1.0 6 votes vote down vote up
private Long getCount(String fieldName) {
  Transaction txn = datastore.newTransaction(
      TransactionOptions.newBuilder()
          .setReadOnly(ReadOnly.newBuilder().build())
          .build()
  );

  QueryResults<ProjectionEntity> results;
  try {
    Query<ProjectionEntity> countQuery = Query.newProjectionEntityQueryBuilder()
        .setKind(SHARD)
        .setNamespace(namespace)
        .setProjection(fieldName)
        .build();

    results = datastore.run(countQuery);
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(results, Spliterator.NONNULL), false)
        .map(entity -> Long.valueOf(entity.getLong(fieldName)))
        .reduce(0L, (valueA, valueB) -> valueA + valueB);
  } finally {
    if (txn.isActive()) {
      txn.rollback();
    }
  }
}
 
Example #2
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: DefaultDatastoreReader.java    From catatumbo with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the given {@link ProjectionQueryRequest} and returns the response.
 * 
 * @param expectedResultType
 *          the expected type of results.
 * @param request
 *          the projection query request
 * @return the query response
 */
public <E> QueryResponse<E> executeProjectionQueryRequest(Class<E> expectedResultType,
    ProjectionQueryRequest request) {
  try {
    GqlQuery.Builder<ProjectionEntity> queryBuilder = Query
        .newGqlQueryBuilder(ResultType.PROJECTION_ENTITY, request.getQuery());
    queryBuilder.setNamespace(entityManager.getEffectiveNamespace());
    queryBuilder.setAllowLiteral(request.isAllowLiterals());
    QueryUtils.applyNamedBindings(queryBuilder, request.getNamedBindings());
    QueryUtils.applyPositionalBindings(queryBuilder, request.getPositionalBindings());
    GqlQuery<ProjectionEntity> gqlQuery = queryBuilder.build();
    QueryResults<ProjectionEntity> results = nativeReader.run(gqlQuery);
    List<E> entities = new ArrayList<>();
    DefaultQueryResponse<E> response = new DefaultQueryResponse<>();
    response.setStartCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    while (results.hasNext()) {
      ProjectionEntity result = results.next();
      E entity = Unmarshaller.unmarshal(result, expectedResultType);
      entities.add(entity);
    }
    response.setResults(entities);
    response.setEndCursor(new DefaultDatastoreCursor(results.getCursorAfter().toUrlSafe()));
    response.setQueryResponseMetadata(
        new DefaultQueryResponseMetadata(
            QueryResponseMetadata.QueryState.forMoreResultsType(results.getMoreResults())));
    // TODO should we invoke PostLoad callback for projected entities?
    return response;
  } catch (DatastoreException exp) {
    throw new EntityManagerException(exp);
  }
}
 
Example #4
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testProjectionQuery() {
  setUpQueryTests();
  // [START datastore_projection_query]
  Query<ProjectionEntity> query = Query.newProjectionEntityQueryBuilder()
      .setKind("Task")
      .setProjection("priority", "percent_complete")
      .build();
  // [END datastore_projection_query]
  assertValidQuery(query);
}
 
Example #5
Source File: ConceptsTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testDistinctOnQuery() {
  setUpQueryTests();
  // [START datastore_distinct_on_query]
  Query<ProjectionEntity> query = Query.newProjectionEntityQueryBuilder()
      .setKind("Task")
      .setProjection("category", "priority")
      .setDistinctOn("category")
      .setOrderBy(OrderBy.asc("category"), OrderBy.asc("priority"))
      .build();
  // [END datastore_distinct_on_query]
  assertValidQuery(query);
}
 
Example #6
Source File: QuerySnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/** Example of creating and running a projection entity query. */
// [TARGET newProjectionEntityQueryBuilder()]
// [VARIABLE "my_kind"]
// [VARIABLE "my_property"]
public QueryResults<ProjectionEntity> newProjectionEntityQuery(String kind, String property) {
  // [START newProjectionEntityQuery]
  Query<ProjectionEntity> query =
      Query.newProjectionEntityQueryBuilder().setKind(kind).addProjection(property).build();
  QueryResults<ProjectionEntity> results = datastore.run(query);
  // Use results
  // [END newProjectionEntityQuery]
  return results;
}
 
Example #7
Source File: ITQuerySnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewProjectionEntityQuery() throws InterruptedException {
  QuerySnippets transactionSnippets = new QuerySnippets(datastore);
  QueryResults<ProjectionEntity> results =
      transactionSnippets.newProjectionEntityQuery(KIND, "description");
  Set<String> resultSet =
      Sets.newHashSet(Iterators.transform(results, ENTITY_TO_DESCRIPTION_FUNCTION));
  while (!resultSet.contains(entity1.getString("description"))
      || !resultSet.contains(entity2.getString("description"))) {
    Thread.sleep(500);
    resultSet = Sets.newHashSet(Iterators.transform(results, ENTITY_TO_DESCRIPTION_FUNCTION));
  }
}
 
Example #8
Source File: ITQuerySnippets.java    From google-cloud-java with Apache License 2.0 4 votes vote down vote up
@Override
public String apply(ProjectionEntity entity) {
  return entity.getString("description");
}
 
Example #9
Source File: Unmarshaller.java    From catatumbo with Apache License 2.0 2 votes vote down vote up
/**
 * Unmarshals the given native ProjectionEntity into an object of given type, entityClass.
 * 
 * @param <T>
 *          target object type
 * @param nativeEntity
 *          the native Entity
 * @param entityClass
 *          the target type
 * @return Object that is equivalent to the given native entity. If the given
 *         <code>datastoreEntity</code> is <code>null</code>, returns <code>null</code>.
 */
public static <T> T unmarshal(ProjectionEntity nativeEntity, Class<T> entityClass) {
  return unmarshalBaseEntity(nativeEntity, entityClass);
}