Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

samples: Add sample snippets for count aggregations #871

Merged
merged 88 commits into from
Oct 21, 2022
Merged
Show file tree
Hide file tree
Changes from 87 commits
Commits
Show all changes
88 commits
Select commit Hold shift + click to select a range
ce4c149
Add method in Datastore client to invoke rpc for aggregation query
jainsahab Aug 29, 2022
100115f
Creating count aggregation and using it to populate Aggregation proto
jainsahab Aug 29, 2022
c1956d8
Moving aggregation builder method to root level aggregation class
jainsahab Aug 30, 2022
493edfa
Introducing RecordQuery to represent queries which returns entity rec…
jainsahab Sep 7, 2022
9c7c4ba
Updating gitignore with patch extension
jainsahab Sep 7, 2022
cf49a37
Setting up structure of Aggregation query and its builder
jainsahab Sep 8, 2022
78fd6c9
Introducing ProtoPreparer to populate the request protos
jainsahab Sep 9, 2022
2ae957a
Delegating responsibility of preparing query proto to QueryPreparer
jainsahab Sep 9, 2022
14ac55f
Populating aggregation query with nested structured query
jainsahab Sep 9, 2022
3ff182f
Delegating responsibility of preparing query proto in GqlQuery to Que…
jainsahab Sep 9, 2022
7de95e6
Removing RecordQuery from the query hierarchy and making it a standal…
jainsahab Sep 12, 2022
d62964f
Populating aggregation query with nested gql query
jainsahab Sep 12, 2022
1f5b1a4
Removing deprecation warning by using assertThrows instead of Expecte…
jainsahab Sep 12, 2022
b69b166
Making DatastoreRpc call aggregation query method on client
jainsahab Sep 12, 2022
9589f5c
Creating response transformer to transform aggregation query response…
jainsahab Sep 13, 2022
2103b80
Implementing aggregation query executor to execute AggergationQuery
jainsahab Sep 13, 2022
775c341
Adding missing assertion statements
jainsahab Sep 13, 2022
8872a55
Creating RetryExecutor to inject it as a dependency in other components
jainsahab Sep 14, 2022
1dfafb7
Making RetryExecutor accept RetrySettings when creating it
jainsahab Sep 14, 2022
f6bf0ce
Revert "Making RetryExecutor accept RetrySettings when creating it"
jainsahab Sep 14, 2022
deb63bf
Revert "Creating RetryExecutor to inject it as a dependency in other …
jainsahab Sep 14, 2022
428e9e3
Introducing RetryAndTraceDatastoreRpcDecorator to have retry and trac…
jainsahab Sep 14, 2022
c86913e
Extracting out the responsibility of preparing ReadOption in it's own…
jainsahab Sep 14, 2022
b235935
Making QueryExecutor to execute query with provided ReadOptions
jainsahab Sep 14, 2022
f1c3379
Exposing readTime to the user
jainsahab Sep 14, 2022
168b864
Ignoring runAggregationQuery method from clirr check
jainsahab Sep 14, 2022
005429b
Making readTime final
jainsahab Sep 15, 2022
dfbdf60
Allowing namespace to be optional in AggregationQuery
jainsahab Sep 15, 2022
0565ba6
Add capability to fetch aggregation result by passing alias
jainsahab Sep 15, 2022
0e8e7b9
Implementing User facing datastore.runAggrgation method to run aggreg…
jainsahab Sep 15, 2022
fc0f0dd
Add integration test for count aggregation
jainsahab Sep 15, 2022
e6cbca6
Add transaction Id support in ReadOptionsProtoPreparer
jainsahab Sep 19, 2022
d205997
Supporting aggregation query with transactions
jainsahab Sep 19, 2022
5097cd6
Allowing user to create Aggregation directly without involving its bu…
jainsahab Sep 19, 2022
6508ff6
Preventing creating duplicated aggregation when creating an aggregati…
jainsahab Sep 19, 2022
5f1e419
Marking RecordQuery implemented method as InternalApi
jainsahab Sep 19, 2022
5e2fcb3
Writing comments and JavaDoc for aggregation query related class
jainsahab Sep 20, 2022
372a2d7
Adding a default implementation in the public interfaces to avoid com…
jainsahab Sep 22, 2022
31e0c5a
Merge branch 'main' into count_feature
jainsahab Sep 22, 2022
2c2cf63
covering a scenario to maintain consistent snapshot when executing ag…
jainsahab Sep 22, 2022
4719ae8
Creating emulator proxy to simulate AggregationQuery response from em…
jainsahab Sep 23, 2022
8edebda
Integration test to execute an aggregation query in a read only trans…
jainsahab Sep 27, 2022
ecdc04e
Merge branch 'main' into count_feature
jainsahab Sep 28, 2022
394a642
Count aggregation samples with structuredQuery and gql query
jainsahab Sep 28, 2022
41cbef7
Count aggregation samples to demonstrate stale read
jainsahab Sep 28, 2022
842df2d
Getting rid off limit operation on count aggregation as same behaviou…
jainsahab Sep 29, 2022
8c81b9f
Removing import statement from javadoc and undo changes in .gitignore…
jainsahab Sep 29, 2022
1584d9f
Using Optional instead of returning null from ReadOptionsProtoPreparer
jainsahab Sep 29, 2022
bc425dd
using assertThat from Truth library
jainsahab Sep 29, 2022
5801641
Removing 'limit' api from count query samples
jainsahab Oct 7, 2022
8479fd2
Merge branch 'main' into count_feature
jainsahab Oct 7, 2022
41df1bc
fixing unit test
jainsahab Oct 7, 2022
1606584
Getting rid off Double braces initialization syntax
jainsahab Oct 7, 2022
ca27e75
Fixing lint
jainsahab Oct 7, 2022
9ff91d9
Getting rid off emulator proxy and using easy mock to check the aggre…
jainsahab Oct 7, 2022
6953efe
Deleting a entity created locally in other test which is causing fail…
jainsahab Oct 7, 2022
d2e1969
Deleting all keys in datastore in integration test so that new test c…
jainsahab Oct 7, 2022
39812d4
Executing two read write transaction simultaneously and verifying the…
jainsahab Oct 7, 2022
2d9e81a
Removing tests to verify serializability as it's an underlying implem…
jainsahab Oct 7, 2022
90ab7cb
Fixing lint
jainsahab Oct 7, 2022
a48b323
Merge branch 'main' into count_feature
jainsahab Oct 10, 2022
aae2620
Adding runAggregationQuery method to reflect config so that it's avai…
jainsahab Oct 10, 2022
c2a8bc7
Merge branch 'count_feature' into count_feature_sample
jainsahab Oct 10, 2022
f9b41b2
Aggregation query samples with limit and order by option
jainsahab Oct 10, 2022
a4cf366
Aggregation query samples with transactions
jainsahab Oct 10, 2022
e265f35
fixing lint and reusing sysoutRule
jainsahab Oct 10, 2022
4a9c7ba
correcting region tag
jainsahab Oct 13, 2022
485212d
simplifying tearDown method
jainsahab Oct 13, 2022
9c93a6c
Merge branch 'main' into count_feature_sample
jainsahab Oct 18, 2022
7d66848
Reverting back to using Task domain for aggregation query samples
jainsahab Oct 18, 2022
1af69af
Limiting tearDown method to delete only Task entities
jainsahab Oct 18, 2022
9871515
Splitting count aggregation query samples into individual java files
jainsahab Oct 19, 2022
6e6a423
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Oct 19, 2022
54ace27
Adding missing header
jainsahab Oct 19, 2022
170590b
Sticking to the practise of deleting the old created data in setUp of…
jainsahab Oct 19, 2022
670face
Moving comment to the top of statement.
jainsahab Oct 19, 2022
67b2602
Making builder syntax multiline
jainsahab Oct 19, 2022
ebc998d
Adding comment describing the purpose of GQL query
jainsahab Oct 19, 2022
9988599
Rephrasing the comment
jainsahab Oct 19, 2022
c3fa6d7
Adding a comment describing the purpose of the GQL query
jainsahab Oct 19, 2022
11a4230
Rephrasing the comment
jainsahab Oct 19, 2022
7189f80
Relocating region tags to include import statments
jainsahab Oct 19, 2022
350ab61
Few styling and comment fixes
jainsahab Oct 19, 2022
abd2b95
Adding comment in the transaction block
jainsahab Oct 19, 2022
1adf105
Adding fullstop to the comment lines
jainsahab Oct 19, 2022
e89fde6
Showcasing with/without alias usage separately
jainsahab Oct 20, 2022
36f82fa
Importing static methods are we are now including import statements i…
jainsahab Oct 20, 2022
de89eb9
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Oct 21, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,13 @@ Samples are in the [`samples/`](https://github.com/googleapis/java-datastore/tre
| --------------------------- | --------------------------------- | ------ |
| Native Image Datastore Sample | [source code](https://github.com/googleapis/java-datastore/blob/main/samples/native-image-sample/src/main/java/com/example/datastore/NativeImageDatastoreSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-datastore&page=editor&open_in_editor=samples/native-image-sample/src/main/java/com/example/datastore/NativeImageDatastoreSample.java) |
| Quickstart Sample | [source code](https://github.com/googleapis/java-datastore/blob/main/samples/snippets/src/main/java/com/example/datastore/QuickstartSample.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-datastore&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/datastore/QuickstartSample.java) |
| Count Aggregation In Transaction | [source code](https://github.com/googleapis/java-datastore/blob/main/samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationInTransaction.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-datastore&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationInTransaction.java) |
| Count Aggregation On Kind | [source code](https://github.com/googleapis/java-datastore/blob/main/samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationOnKind.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-datastore&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationOnKind.java) |
| Count Aggregation With Gql Query | [source code](https://github.com/googleapis/java-datastore/blob/main/samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationWithGqlQuery.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-datastore&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationWithGqlQuery.java) |
| Count Aggregation With Limit | [source code](https://github.com/googleapis/java-datastore/blob/main/samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationWithLimit.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-datastore&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationWithLimit.java) |
| Count Aggregation With Order By | [source code](https://github.com/googleapis/java-datastore/blob/main/samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationWithOrderBy.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-datastore&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationWithOrderBy.java) |
| Count Aggregation With Property Filter | [source code](https://github.com/googleapis/java-datastore/blob/main/samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationWithPropertyFilter.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-datastore&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationWithPropertyFilter.java) |
| Count Aggregation With Stale Read | [source code](https://github.com/googleapis/java-datastore/blob/main/samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationWithStaleRead.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-datastore&page=editor&open_in_editor=samples/snippets/src/main/java/com/example/datastore/aggregation/CountAggregationWithStaleRead.java) |
| Task List | [source code](https://github.com/googleapis/java-datastore/blob/main/samples/snippets/src/main/java/com/google/datastore/snippets/TaskList.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-datastore&page=editor&open_in_editor=samples/snippets/src/main/java/com/google/datastore/snippets/TaskList.java) |


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.datastore.aggregation;

// [START datastore_count_aggregation_query_in_transaction]

import static com.google.cloud.datastore.aggregation.Aggregation.count;

import com.google.cloud.datastore.AggregationQuery;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.Datastore.TransactionCallable;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.EntityQuery;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.StructuredQuery.PropertyFilter;
import com.google.common.collect.Iterables;

public class CountAggregationInTransaction {

public static void invoke() {
// Instantiates a client.
Datastore datastore = DatastoreOptions.getDefaultInstance().getService();

// The kind for the new entity.
String kind = "Task";

Key task1Key = datastore.newKeyFactory().setKind(kind).newKey("task1");
Key task2Key = datastore.newKeyFactory().setKind(kind).newKey("task2");

// Save all the tasks.
datastore.put(
Entity.newBuilder(task1Key).set("owner", "john").build(),
Entity.newBuilder(task2Key).set("owner", "john").build());

// Using transactions to maintain consistent application state.
datastore.runInTransaction(
(TransactionCallable<Void>)
transaction -> {
jainsahab marked this conversation as resolved.
Show resolved Hide resolved
// Create a query to get the count of all tasks of owner 'John'.
EntityQuery tasksOfJohn =
Query.newEntityQueryBuilder()
.setKind(kind)
.setFilter(PropertyFilter.eq("owner", "john"))
.build();
AggregationQuery totalTasksQuery =
Query.newAggregationQueryBuilder()
.over(tasksOfJohn)
.addAggregation(count().as("tasks_count"))
.build();

// Executing aggregation query in the ongoing transaction.
Long tasksCount =
Iterables.getOnlyElement(transaction.runAggregation(totalTasksQuery))
.get("tasks_count");

if (tasksCount < 2) {
Key newTaskKey = datastore.newKeyFactory().setKind(kind).newKey("task3");
Entity newTask = Entity.newBuilder(newTaskKey).set("owner", "john").build();
// Inserting a new entity in the transaction.
transaction.put(newTask);
} else {
System.out.printf("Found existing %d tasks, rolling back", tasksCount);
throw new Exception("User 'John' cannot have more than 2 tasks");
}
return null;
});
}
}
// [END datastore_count_aggregation_query_in_transaction]
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.datastore.aggregation;

// [START datastore_count_aggregation_query_on_kind]
import static com.google.cloud.datastore.aggregation.Aggregation.count;

import com.google.cloud.datastore.AggregationQuery;
import com.google.cloud.datastore.AggregationResult;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.EntityQuery;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.Query;
import com.google.common.collect.Iterables;

public class CountAggregationOnKind {
// Instantiates a client.
private static final Datastore datastore = DatastoreOptions.getDefaultInstance().getService();

// The kind for the new entity.
private static final String kind = "Task";

// Setting up Tasks in database
private static void setUpTasks() {
Key task1Key = datastore.newKeyFactory().setKind(kind).newKey("task1");
Key task2Key = datastore.newKeyFactory().setKind(kind).newKey("task2");
Key task3Key = datastore.newKeyFactory().setKind(kind).newKey("task3");

// Save all the tasks.
datastore.put(
Entity.newBuilder(task1Key).set("done", true).build(),
Entity.newBuilder(task2Key).set("done", false).build(),
Entity.newBuilder(task3Key).set("done", true).build());
}

// Accessing aggregation result by the generated alias.
private static void usageWithGeneratedAlias() {
EntityQuery selectAllTasks = Query.newEntityQueryBuilder().setKind(kind).build();
// Creating an aggregation query to get the count of all tasks.
AggregationQuery allTasksCountQuery =
Query.newAggregationQueryBuilder()
.over(selectAllTasks)
.addAggregation(count())
.build();
// Executing aggregation query.
AggregationResult aggregationResult =
Iterables.getOnlyElement(datastore.runAggregation(allTasksCountQuery));

System.out.printf(
"Total tasks (accessible from default alias) is %d",
aggregationResult.get("property_1")); // 3
}

// Accessing aggregation result by the provided custom alias.
private static void usageWithCustomAlias() {
EntityQuery selectAllTasks = Query.newEntityQueryBuilder().setKind(kind).build();
// Creating an aggregation query to get the count of all tasks.
AggregationQuery allTasksCountQuery =
Query.newAggregationQueryBuilder()
.over(selectAllTasks)
// passing 'total_count' as alias in the aggregation query.
.addAggregation(count().as("total_count"))
.build();
// Executing aggregation query.
AggregationResult aggregationResult =
Iterables.getOnlyElement(datastore.runAggregation(allTasksCountQuery));

System.out.printf("Total tasks count is %d", aggregationResult.get("total_count")); // 3
}

public static void invoke() {
setUpTasks();
usageWithGeneratedAlias();
usageWithCustomAlias();
}
}
// [END datastore_count_aggregation_query_on_kind]
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.datastore.aggregation;

// [START datastore_count_aggregation_query_gql]
import com.google.cloud.datastore.AggregationQuery;
import com.google.cloud.datastore.AggregationResult;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.GqlQuery;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.Query;
import com.google.common.collect.Iterables;

public class CountAggregationWithGqlQuery {

public static void invoke() {
// Instantiates a client.
Datastore datastore = DatastoreOptions.getDefaultInstance().getService();

// The kind for the new entity.
String kind = "Task";

Key task1Key = datastore.newKeyFactory().setKind(kind).newKey("task1");
Key task2Key = datastore.newKeyFactory().setKind(kind).newKey("task2");
Key task3Key = datastore.newKeyFactory().setKind(kind).newKey("task3");

// Save all the tasks.
datastore.put(
Entity.newBuilder(task1Key).set("done", true).build(),
Entity.newBuilder(task2Key).set("done", false).build(),
Entity.newBuilder(task3Key).set("done", true).build());

// Create a GQL query to get the count of all tasks.
GqlQuery<?> selectAllTasks =
jainsahab marked this conversation as resolved.
Show resolved Hide resolved
Query.newGqlQueryBuilder(
"AGGREGATE COUNT(*) AS total_count, COUNT_UP_TO(2) AS count_with_limit "
+ "OVER (SELECT * FROM Task)")
.setAllowLiteral(true)
.build();
// Create the aggregation query builder and set the query.
AggregationQuery allTasksCountQuery =
Query.newAggregationQueryBuilder().over(selectAllTasks).build();
// Executing aggregation query.
AggregationResult allTasksCountQueryResult =
Iterables.getOnlyElement(datastore.runAggregation(allTasksCountQuery));

System.out.printf(
"We have at least %d tasks", allTasksCountQueryResult.get("count_with_limit")); // 2
System.out.printf("Total tasks count is %d", allTasksCountQueryResult.get("total_count")); // 3

// Create a query to get the count of all completed tasks.
GqlQuery<?> completedTasks =
jainsahab marked this conversation as resolved.
Show resolved Hide resolved
Query.newGqlQueryBuilder(
"AGGREGATE COUNT(*) AS total_completed_count "
+ "OVER (SELECT * FROM Task WHERE done = true)")
.setAllowLiteral(true)
.build();
// Create the aggregation query builder and set the query.
AggregationQuery completedTasksCountQuery =
Query.newAggregationQueryBuilder().over(completedTasks).build();

// Executing aggregation query.
AggregationResult completedTasksCountQueryResult =
Iterables.getOnlyElement(datastore.runAggregation(completedTasksCountQuery));

System.out.printf(
"Total completed tasks count is %d",
completedTasksCountQueryResult.get("total_completed_count")); // 2
}
}
// [END datastore_count_aggregation_query_gql]
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.datastore.aggregation;

// [START datastore_count_aggregation_query_with_limit]

import static com.google.cloud.datastore.aggregation.Aggregation.count;

import com.google.cloud.datastore.AggregationQuery;
import com.google.cloud.datastore.AggregationResult;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.EntityQuery;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.Query;
import com.google.common.collect.Iterables;

public class CountAggregationWithLimit {
public static void invoke() {
// Instantiates a client.
Datastore datastore = DatastoreOptions.getDefaultInstance().getService();

// The kind for the new entity.
String kind = "Task";

Key task1Key = datastore.newKeyFactory().setKind(kind).newKey("task1");
Key task2Key = datastore.newKeyFactory().setKind(kind).newKey("task2");
Key task3Key = datastore.newKeyFactory().setKind(kind).newKey("task3");

// Save all the tasks.
datastore.put(
Entity.newBuilder(task1Key).set("done", true).build(),
Entity.newBuilder(task2Key).set("done", false).build(),
Entity.newBuilder(task3Key).set("done", true).build());

EntityQuery selectAllTasks = Query.newEntityQueryBuilder()
.setKind(kind)
.setLimit(2)
.build();
// Creating an aggregation query to get the count of all tasks.
AggregationQuery allTasksCountQuery =
Query.newAggregationQueryBuilder()
.over(selectAllTasks)
.addAggregation(count().as("at_least"))
.build();
// Executing aggregation query.
AggregationResult limitQueryResult =
Iterables.getOnlyElement(datastore.runAggregation(allTasksCountQuery));

System.out.printf("We have at least %d tasks", limitQueryResult.get("at_least")); // 2
}
}
// [END datastore_count_aggregation_query_with_limit]
Loading