jestro
jestro

Reputation: 2593

Is this the correct way to query by key with Java in Google Cloud Datastore?

// Use Query.Builder to assemble a query
Query.Builder q = Query.newBuilder();
q.addKindBuilder().setName("Trivia");
q.setFilter(makeFilter("__key__", PropertyFilter.Operator.EQUAL,
makeValue(makeKey("Trivia", "hgtg"))));

// Assemble a RunQueryRequest
RunQueryRequest request = RunQueryRequest.newBuilder().setQuery(q).build();
RunQueryResponse response = Main.datastore.runQuery(request);

Where the Key is hgtg and the Kind is Trivia.

Also, would this query be considered Strongly Consistent? As far as I can tell this is only querying one Entity Group so it should be Strongly Consistent.

Thanks!

EDIT: I'm asking about Google Cloud Datastore which has a different Java API than App Engine.

Upvotes: 1

Views: 781

Answers (1)

David
David

Reputation: 5519

As per the Cloud Datastore "getting started in Java" page you should rather use a LookupRequest :

  // Create an RPC request to begin a new transaction.
  BeginTransactionRequest.Builder treq = BeginTransactionRequest.newBuilder();
  // Execute the RPC synchronously.
  BeginTransactionResponse tres = datastore.beginTransaction(treq.build());
  // Get the transaction handle from the response.
  ByteString tx = tres.getTransaction();

  // Create an RPC request to get entities by key.
  LookupRequest.Builder lreq = LookupRequest.newBuilder();
  // Set the entity key with only one `path_element`: no parent.
  Key.Builder key = Key.newBuilder().addPathElement(
      Key.PathElement.newBuilder()
      .setKind("Trivia")
      .setName("hgtg"));
  // Add one key to the lookup request.
  lreq.addKey(key);
  // Set the transaction, so we get a consistent snapshot of the
  // entity at the time the transaction started.
  lreq.getReadOptionsBuilder().setTransaction(tx);
  // Execute the RPC and get the response.
  LookupResponse lresp = datastore.lookup(lreq.build());
  // Create an RPC request to commit the transaction.
  CommitRequest.Builder creq = CommitRequest.newBuilder();
  // Set the transaction to commit.
  creq.setTransaction(tx);
  Entity entity;
  if (lresp.getFoundCount() > 0) {
    entity = lresp.getFound(0).getEntity();
  }

As for the strong consistency, a lookup is always strongly consistent as written here :

Remember, if you do a lookup, an ancestor query, or any operation within a transaction, you will always see the most recently written data.

Upvotes: 1

Related Questions