diff --git a/samples/snippets/src/main/java/com/example/firestore/Quickstart.java b/samples/snippets/src/main/java/com/example/firestore/Quickstart.java index ffbc1f355..f53cd27a3 100644 --- a/samples/snippets/src/main/java/com/example/firestore/Quickstart.java +++ b/samples/snippets/src/main/java/com/example/firestore/Quickstart.java @@ -20,8 +20,10 @@ import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.firestore.DocumentReference; // [START fs_include_dependencies] +// [START firestore_setup_dependencies] import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.FirestoreOptions; +// [END firestore_setup_dependencies] // [END fs_include_dependencies] import com.google.cloud.firestore.QueryDocumentSnapshot; import com.google.cloud.firestore.QuerySnapshot; @@ -44,19 +46,23 @@ public class Quickstart { */ public Quickstart() { // [START fs_initialize] + // [START firestore_setup_client_create] Firestore db = FirestoreOptions.getDefaultInstance().getService(); + // [END firestore_setup_client_create] // [END fs_initialize] this.db = db; } public Quickstart(String projectId) throws Exception { // [START fs_initialize_project_id] + // [START firestore_setup_client_create_with_project_id] FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance().toBuilder() .setProjectId(projectId) .setCredentials(GoogleCredentials.getApplicationDefault()) .build(); Firestore db = firestoreOptions.getService(); + // [END firestore_setup_client_create_with_project_id] // [END fs_initialize_project_id] this.db = db; } @@ -74,6 +80,7 @@ void addDocument(String docName) throws Exception { switch (docName) { case "alovelace": { // [START fs_add_data_1] + // [START firestore_setup_dataset_pt1] DocumentReference docRef = db.collection("users").document("alovelace"); // Add document data with id "alovelace" using a hashmap Map data = new HashMap<>(); @@ -85,11 +92,13 @@ void addDocument(String docName) throws Exception { // ... // result.get() blocks on response System.out.println("Update time : " + result.get().getUpdateTime()); + // [END firestore_setup_dataset_pt1] // [END fs_add_data_1] break; } case "aturing": { // [START fs_add_data_2] + // [START firestore_setup_dataset_pt2] DocumentReference docRef = db.collection("users").document("aturing"); // Add document data with an additional field ("middle") Map data = new HashMap<>(); @@ -100,6 +109,7 @@ void addDocument(String docName) throws Exception { ApiFuture result = docRef.set(data); System.out.println("Update time : " + result.get().getUpdateTime()); + // [END firestore_setup_dataset_pt2] // [END fs_add_data_2] break; } diff --git a/samples/snippets/src/main/java/com/example/firestore/snippets/ListenDataSnippets.java b/samples/snippets/src/main/java/com/example/firestore/snippets/ListenDataSnippets.java index dc4958737..8bc9bc146 100644 --- a/samples/snippets/src/main/java/com/example/firestore/snippets/ListenDataSnippets.java +++ b/samples/snippets/src/main/java/com/example/firestore/snippets/ListenDataSnippets.java @@ -54,6 +54,7 @@ Map listenToDocument() throws Exception { final SettableApiFuture> future = SettableApiFuture.create(); // [START listen_to_document] + // [START firestore_listen_document] DocumentReference docRef = db.collection("cities").document("SF"); docRef.addSnapshotListener(new EventListener() { @Override @@ -76,6 +77,7 @@ public void onEvent(@Nullable DocumentSnapshot snapshot, // [END_EXCLUDE] } }); + // [END firestore_listen_document] // [END listen_to_document] return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); @@ -88,6 +90,7 @@ List listenForMultiple() throws Exception { final SettableApiFuture> future = SettableApiFuture.create(); // [START listen_to_multiple] + // [START firestore_listen_query_snapshots] db.collection("cities") .whereEqualTo("state", "CA") .addSnapshotListener(new EventListener() { @@ -113,6 +116,7 @@ public void onEvent(@Nullable QuerySnapshot snapshots, // [END_EXCLUDE] } }); + // [END firestore_listen_query_snapshots] // [END listen_to_multiple] return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); @@ -125,6 +129,7 @@ List listenForChanges() throws Exception { SettableApiFuture> future = SettableApiFuture.create(); // [START listen_for_changes] + // [START firestore_listen_query_changes] db.collection("cities") .whereEqualTo("state", "CA") .addSnapshotListener(new EventListener() { @@ -158,6 +163,7 @@ public void onEvent(@Nullable QuerySnapshot snapshots, // [END_EXCLUDE] } }); + // [END firestore_listen_query_changes] // [END listen_for_changes] return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); @@ -168,6 +174,7 @@ public void onEvent(@Nullable QuerySnapshot snapshots, */ void detachListener() { // [START detach_errors] + // [START firestore_listen_detach] Query query = db.collection("cities"); ListenerRegistration registration = query.addSnapshotListener( new EventListener() { @@ -184,6 +191,7 @@ public void onEvent(@Nullable QuerySnapshot snapshots, // Stop listening to changes registration.remove(); + // [END firestore_listen_detach] // [END detach_errors] } @@ -192,6 +200,7 @@ public void onEvent(@Nullable QuerySnapshot snapshots, */ void listenErrors() { // [START listen_errors] + // [START firestore_listen_handle_error] db.collection("cities") .addSnapshotListener(new EventListener() { @Override @@ -209,6 +218,7 @@ public void onEvent(@Nullable QuerySnapshot snapshots, } } }); + // [END firestore_listen_handle_error] // [END listen_errors] } diff --git a/samples/snippets/src/main/java/com/example/firestore/snippets/ManageDataSnippets.java b/samples/snippets/src/main/java/com/example/firestore/snippets/ManageDataSnippets.java index 7a9b4f527..926d9c019 100644 --- a/samples/snippets/src/main/java/com/example/firestore/snippets/ManageDataSnippets.java +++ b/samples/snippets/src/main/java/com/example/firestore/snippets/ManageDataSnippets.java @@ -53,6 +53,7 @@ class ManageDataSnippets { */ Map addSimpleDocumentAsMap() throws Exception { // [START fs_add_doc_as_map] + // [START firestore_data_set_from_map] // Create a Map to store the data we want to set Map docData = new HashMap<>(); docData.put("name", "Los Angeles"); @@ -64,6 +65,7 @@ Map addSimpleDocumentAsMap() throws Exception { // ... // future.get() blocks on response System.out.println("Update time : " + future.get().getUpdateTime()); + // [END firestore_data_set_from_map] // [END fs_add_doc_as_map] return docData; } @@ -75,6 +77,7 @@ Map addSimpleDocumentAsMap() throws Exception { */ Map addDocumentWithDifferentDataTypes() throws Exception { // [START fs_add_doc_data_types] + // [START firestore_data_set_from_map_nested] Map docData = new HashMap<>(); docData.put("stringExample", "Hello, World"); docData.put("booleanExample", false); @@ -93,6 +96,7 @@ Map addDocumentWithDifferentDataTypes() throws Exception { ApiFuture future = db.collection("data").document("one").set(docData); System.out.println("Update time : " + future.get().getUpdateTime()); + // [END firestore_data_set_from_map_nested] // [END fs_add_doc_data_types] return docData; @@ -105,11 +109,13 @@ Map addDocumentWithDifferentDataTypes() throws Exception { */ City addSimpleDocumentAsEntity() throws Exception { // [START fs_add_simple_doc_as_entity] + // [START firestore_data_set_from_custom_type] City city = new City("Los Angeles", "CA", "USA", false, 3900000L, Arrays.asList("west_coast", "socal")); ApiFuture future = db.collection("cities").document("LA").set(city); // block on response if required System.out.println("Update time : " + future.get().getUpdateTime()); + // [END firestore_data_set_from_custom_type] // [END fs_add_simple_doc_as_entity] return city; @@ -120,7 +126,9 @@ City addSimpleDocumentAsEntity() throws Exception { */ void setRequiresId(Map data) { // [START fs_set_requires_id] + // [START firestore_data_set_id_specified] db.collection("cities").document("new-city-id").set(data); + // [END firestore_data_set_id_specified] // [END fs_set_requires_id] } @@ -132,12 +140,14 @@ void setRequiresId(Map data) { */ String addDocumentDataWithAutoGeneratedId() throws Exception { // [START fs_add_doc_data_with_auto_id] + // [START firestore_data_set_id_random_collection] // Add document data with auto-generated id. Map data = new HashMap<>(); data.put("name", "Tokyo"); data.put("country", "Japan"); ApiFuture addedDocRef = db.collection("cities").add(data); System.out.println("Added document with ID: " + addedDocRef.get().getId()); + // [END firestore_data_set_id_random_collection] // [END fs_add_doc_data_with_auto_id] return addedDocRef.get().getId(); @@ -152,12 +162,14 @@ String addDocumentDataAfterAutoGeneratingId() throws Exception { City data = new City(); // [START fs_add_doc_data_after_auto_id] + // [START firestore_data_set_id_random_document_ref] // Add document data after generating an id. DocumentReference addedDocRef = db.collection("cities").document(); System.out.println("Added document with ID: " + addedDocRef.getId()); // later... ApiFuture writeResult = addedDocRef.set(data); + // [END firestore_data_set_id_random_document_ref] // [END fs_add_doc_data_after_auto_id] // writeResult.get() blocks on operation @@ -169,6 +181,7 @@ String addDocumentDataAfterAutoGeneratingId() throws Exception { void updateSimpleDocument() throws Exception { db.collection("cities").document("DC").set(new City("Washington D.C.")).get(); // [START fs_update_doc] + // [START firestore_data_set_field] // Update an existing document DocumentReference docRef = db.collection("cities").document("DC"); @@ -178,6 +191,7 @@ void updateSimpleDocument() throws Exception { // ... WriteResult result = future.get(); System.out.println("Write result: " + result); + // [END firestore_data_set_field] // [END fs_update_doc] } @@ -203,6 +217,7 @@ void updateUsingMap() throws Exception { /** Partially update fields of a document using a map (field => value). */ void updateAndCreateIfMissing() throws Exception { // [START fs_update_create_if_missing] + // [START firestore_data_set_doc_upsert] //asynchronously update doc, create the document if missing Map update = new HashMap<>(); update.put("capital", true); @@ -214,6 +229,7 @@ void updateAndCreateIfMissing() throws Exception { .set(update, SetOptions.merge()); // ... System.out.println("Update time : " + writeResult.get().getUpdateTime()); + // [END firestore_data_set_doc_upsert] // [END fs_update_create_if_missing] } @@ -221,6 +237,7 @@ void updateAndCreateIfMissing() throws Exception { void updateNestedFields() throws Exception { //CHECKSTYLE OFF: VariableDeclarationUsageDistance // [START fs_update_nested_fields] + // [START firestore_data_set_nested_fields] // Create an initial document to update DocumentReference frankDocRef = db.collection("users").document("frank"); Map initialData = new HashMap<>(); @@ -246,6 +263,7 @@ void updateNestedFields() throws Exception { ApiFuture writeResult = frankDocRef.update(updates); // ... System.out.println("Update time : " + writeResult.get().getUpdateTime()); + // [END firestore_data_set_nested_fields] // [END fs_update_nested_fields] //CHECKSTYLE ON: VariableDeclarationUsageDistance } @@ -255,16 +273,19 @@ void updateServerTimestamp() throws Exception { db.collection("objects").document("some-id").set(new HashMap()).get(); // [START fs_update_server_timestamp] + // [START firestore_data_set_server_timestamp] DocumentReference docRef = db.collection("objects").document("some-id"); // Update the timestamp field with the value from the server ApiFuture writeResult = docRef.update("timestamp", FieldValue.serverTimestamp()); System.out.println("Update time : " + writeResult.get()); + // [END firestore_data_set_server_timestamp] // [END fs_update_server_timestamp] } /** Update array fields in a document. **/ void updateDocumentArray() throws Exception { // [START fs_update_document_array] + // [START firestore_data_set_array_operations] DocumentReference washingtonRef = db.collection("cities").document("DC"); // Atomically add a new region to the "regions" array field. @@ -276,6 +297,7 @@ void updateDocumentArray() throws Exception { ApiFuture arrayRm = washingtonRef.update("regions", FieldValue.arrayRemove("east_coast")); System.out.println("Update time : " + arrayRm.get()); + // [END firestore_data_set_array_operations] // [END fs_update_document_array] } @@ -286,12 +308,14 @@ void deleteFields() throws Exception { db.collection("cities").document("BJ").set(city).get(); // [START fs_delete_fields] + // [START firestore_data_delete_field] DocumentReference docRef = db.collection("cities").document("BJ"); Map updates = new HashMap<>(); updates.put("capital", FieldValue.delete()); // Update and delete the "capital" field in the document ApiFuture writeResult = docRef.update(updates); System.out.println("Update time : " + writeResult.get()); + // [END firestore_data_delete_field] // [END fs_delete_fields] } @@ -299,14 +323,17 @@ void deleteFields() throws Exception { void deleteDocument() throws Exception { db.collection("cities").document("DC").set(new City("Washington, D.C.")).get(); // [START fs_delete_doc] + // [START firestore_data_delete_doc] // asynchronously delete a document ApiFuture writeResult = db.collection("cities").document("DC").delete(); // ... System.out.println("Update time : " + writeResult.get().getUpdateTime()); + // [END firestore_data_delete_doc] // [END fs_delete_doc] } // [START fs_delete_collection] + // [START firestore_data_delete_collection] /** Delete a collection in batches to avoid out-of-memory errors. * Batch size may be tuned based on document size (atmost 1MB) and application requirements. */ @@ -329,6 +356,7 @@ void deleteCollection(CollectionReference collection, int batchSize) { System.err.println("Error deleting collection : " + e.getMessage()); } } + // [END firestore_data_delete_collection] // [END fs_delete_collection] /** Run a simple transaction to perform a field value increment. @@ -337,6 +365,7 @@ void deleteCollection(CollectionReference collection, int batchSize) { */ ApiFuture runSimpleTransaction() throws Exception { // [START fs_run_simple_transaction] + // [START firestore_transaction_document_update] // Initialize doc final DocumentReference docRef = db.collection("cities").document("SF"); City city = new City("SF"); @@ -353,6 +382,7 @@ ApiFuture runSimpleTransaction() throws Exception { return null; }); // block on transaction operation using transaction.get() + // [END firestore_transaction_document_update] // [END fs_run_simple_transaction] return futureTransaction; } @@ -369,6 +399,7 @@ String returnInfoFromTransaction(long population) throws Exception { // Block until transaction is complete is using transaction.get() db.collection("cities").document("SF").set(map).get(); // [START fs_return_info_transaction] + // [START firestore_transaction_document_update_conditional] final DocumentReference docRef = db.collection("cities").document("SF"); ApiFuture futureTransaction = db.runTransaction(transaction -> { DocumentSnapshot snapshot = transaction.get(docRef).get(); @@ -383,6 +414,7 @@ String returnInfoFromTransaction(long population) throws Exception { }); // Print information retrieved from transaction System.out.println(futureTransaction.get()); + // [END firestore_transaction_document_update_conditional] // [END fs_return_info_transaction] return futureTransaction.get(); } @@ -393,6 +425,7 @@ void writeBatch() throws Exception { db.collection("cities").document("LA").set(new City()).get(); // [START fs_write_batch] + // [START firestore_data_batch_writes] // Get a new write batch WriteBatch batch = db.batch(); @@ -415,6 +448,7 @@ void writeBatch() throws Exception { for (WriteResult result :future.get()) { System.out.println("Update time : " + result.getUpdateTime()); } + // [END firestore_data_batch_writes] // [END fs_write_batch] } @@ -424,11 +458,13 @@ public void updateDocumentIncrement() throws ExecutionException, InterruptedExce db.collection("cities").document("DC").set(city).get(); // [START fs_update_document_increment] + // [START firestore_data_set_numeric_increment] DocumentReference washingtonRef = db.collection("cities").document("DC"); // Atomically increment the population of the city by 50. final ApiFuture updateFuture = washingtonRef .update("population", FieldValue.increment(50)); + // [END firestore_data_set_numeric_increment] // [END fs_update_document_increment] updateFuture.get(); } diff --git a/samples/snippets/src/main/java/com/example/firestore/snippets/QueryDataSnippets.java b/samples/snippets/src/main/java/com/example/firestore/snippets/QueryDataSnippets.java index 20ce9cc29..ee9c5a93c 100644 --- a/samples/snippets/src/main/java/com/example/firestore/snippets/QueryDataSnippets.java +++ b/samples/snippets/src/main/java/com/example/firestore/snippets/QueryDataSnippets.java @@ -52,6 +52,7 @@ class QueryDataSnippets { void prepareExamples() throws Exception { // [START fs_query_create_examples] + // [START firestore_query_filter_dataset] CollectionReference cities = db.collection("cities"); List> futures = new ArrayList<>(); futures.add( @@ -101,6 +102,7 @@ void prepareExamples() throws Exception { Arrays.asList("jingjinji", "hebei")))); // (optional) block on documents successfully added ApiFutures.allAsList(futures).get(); + // [END firestore_query_filter_dataset] // [END fs_query_create_examples] } @@ -111,6 +113,7 @@ void prepareExamples() throws Exception { */ Query createAQuery() throws Exception { // [START fs_create_query] + // [START firestore_query_filter_eq_boolean] // Create a reference to the cities collection CollectionReference cities = db.collection("cities"); // Create a query against the collection. @@ -121,6 +124,7 @@ Query createAQuery() throws Exception { for (DocumentSnapshot document : querySnapshot.get().getDocuments()) { System.out.println(document.getId()); } + // [END firestore_query_filter_eq_boolean] // [END fs_create_query] return query; } @@ -132,6 +136,7 @@ Query createAQuery() throws Exception { */ Query createAQueryAlternate() throws Exception { // [START fs_create_query_country] + // [START firestore_query_filter_eq_string] // Create a reference to the cities collection CollectionReference cities = db.collection("cities"); // Create a query against the collection. @@ -142,6 +147,7 @@ Query createAQueryAlternate() throws Exception { for (DocumentSnapshot document : querySnapshot.get().getDocuments()) { System.out.println(document.getId()); } + // [END firestore_query_filter_eq_string] // [END fs_create_query_country] return query; } @@ -156,9 +162,11 @@ List createSimpleQueries() { CollectionReference cities = db.collection("cities"); // [START fs_simple_queries] + // [START firestore_query_filter_single_examples] Query stateQuery = cities.whereEqualTo("state", "CA"); Query populationQuery = cities.whereLessThan("population", 1000000L); Query nameQuery = cities.whereGreaterThanOrEqualTo("name", "San Francisco"); + // [END firestore_query_filter_single_examples] // [END fs_simple_queries] querys.add(stateQuery); @@ -174,8 +182,10 @@ List createSimpleQueries() { */ Query createArrayQuery() { // [START fs_array_contains_filter] + // [START firestore_query_filter_array_contains] CollectionReference citiesRef = db.collection("cities"); Query westCoastQuery = citiesRef.whereArrayContains("regions", "west_coast"); + // [END firestore_query_filter_array_contains] // [END fs_array_contains_filter] return westCoastQuery; @@ -191,7 +201,9 @@ Query createArrayQuery() { Query createChainedQuery() { CollectionReference cities = db.collection("cities"); // [START fs_chained_query] + // [START firestore_query_filter_compound_multi_eq] Query chainedQuery1 = cities.whereEqualTo("state", "CO").whereEqualTo("name", "Denver"); + // [END firestore_query_filter_compound_multi_eq] // [END fs_chained_query] return chainedQuery1; } @@ -205,7 +217,9 @@ Query createChainedQuery() { Query createCompositeIndexChainedQuery() { CollectionReference cities = db.collection("cities"); // [START fs_composite_index_chained_query] + // [START firestore_query_filter_compound_multi_eq_lt] Query chainedQuery2 = cities.whereEqualTo("state", "CA").whereLessThan("population", 1000000L); + // [END firestore_query_filter_compound_multi_eq_lt] // [END fs_composite_index_chained_query] return chainedQuery2; } @@ -218,9 +232,11 @@ Query createCompositeIndexChainedQuery() { Query createRangeQuery() { CollectionReference cities = db.collection("cities"); // [START fs_range_query] + // [START firestore_query_filter_range_valid] Query validQuery1 = cities.whereGreaterThanOrEqualTo("state", "CA").whereLessThanOrEqualTo("state", "IN"); Query validQuery2 = cities.whereEqualTo("state", "CA").whereGreaterThan("population", 1000000); + // [END firestore_query_filter_range_valid] // [END fs_range_query] return validQuery1; } @@ -234,8 +250,10 @@ Query createInvalidRangeQuery() { CollectionReference cities = db.collection("cities"); // Violates constraint : range operators are limited to a single field // [START fs_invalid_range_query] + // [START firestore_query_filter_range_invalid] Query invalidRangeQuery = cities.whereGreaterThanOrEqualTo("state", "CA").whereGreaterThan("population", 100000); + // [END firestore_query_filter_range_invalid] // [END fs_invalid_range_query] return invalidRangeQuery; } @@ -248,7 +266,9 @@ Query createInvalidRangeQuery() { Query createOrderByNameWithLimitQuery() { CollectionReference cities = db.collection("cities"); // [START fs_order_by_name_limit_query] + // [START firestore_query_order_limit] Query query = cities.orderBy("name").limit(3); + // [END firestore_query_order_limit] // [END fs_order_by_name_limit_query] return query; } @@ -261,7 +281,9 @@ Query createOrderByNameWithLimitQuery() { Query createOrderByNameWithLimitToLastQuery() { CollectionReference cities = db.collection("cities"); // [START fs_order_by_name_limit_query] + // [START firestore_query_order_limit] Query query = cities.orderBy("name").limitToLast(3); + // [END firestore_query_order_limit] // [END fs_order_by_name_limit_query] return query; } @@ -274,7 +296,9 @@ Query createOrderByNameWithLimitToLastQuery() { Query createOrderByCountryAndPopulation() { CollectionReference cities = db.collection("cities"); // [START fs_order_by_country_population] + // [START firestore_query_order_multi] Query query = cities.orderBy("state").orderBy("population", Direction.DESCENDING); + // [END firestore_query_order_multi] // [END fs_order_by_country_population] return query; } @@ -287,7 +311,9 @@ Query createOrderByCountryAndPopulation() { Query createOrderByNameDescWithLimitQuery() { CollectionReference cities = db.collection("cities"); // [START fs_order_by_name_desc_limit_query] + // [START firestore_query_order_desc_limit] Query query = cities.orderBy("name", Direction.DESCENDING).limit(3); + // [END firestore_query_order_desc_limit] // [END fs_order_by_name_desc_limit_query] return query; } @@ -300,7 +326,9 @@ Query createOrderByNameDescWithLimitQuery() { Query createWhereWithOrderByAndLimitQuery() { CollectionReference cities = db.collection("cities"); // [START fs_where_order_by_limit_query] + // [START firestore_query_order_limit_field_valid] Query query = cities.whereGreaterThan("population", 2500000L).orderBy("population").limit(2); + // [END firestore_query_order_limit_field_valid] // [END fs_where_order_by_limit_query] return query; } @@ -329,7 +357,9 @@ Query createInvalidRangeWithOrderByQuery() { CollectionReference cities = db.collection("cities"); // Violates the constraint that range and order by are required to be on the same field // [START fs_invalid_range_order_by_query] + // [START firestore_query_order_field_invalid] Query query = cities.whereGreaterThan("population", 2500000L).orderBy("country"); + // [END firestore_query_order_field_invalid] // [END fs_invalid_range_order_by_query] return query; } @@ -342,7 +372,9 @@ Query createInvalidRangeWithOrderByQuery() { Query createStartAtFieldQueryCursor() { CollectionReference cities = db.collection("cities"); // [START fs_start_at_field_query_cursor] + // [START firestore_query_cursor_start_at_field_value_single] Query query = cities.orderBy("population").startAt(4921000L); + // [END firestore_query_cursor_start_at_field_value_single] // [END fs_start_at_field_query_cursor] return query; } @@ -355,7 +387,9 @@ Query createStartAtFieldQueryCursor() { Query createEndAtFieldQueryCursor() { CollectionReference cities = db.collection("cities"); // [START fs_end_at_field_query_cursor] + // [START firestore_query_cursor_end_at_field_value_single] Query query = cities.orderBy("population").endAt(4921000L); + // [END firestore_query_cursor_end_at_field_value_single] // [END fs_end_at_field_query_cursor] return query; } @@ -363,12 +397,14 @@ Query createEndAtFieldQueryCursor() { /* Create queries with multiple cursor conditions. */ void createMultipleCursorConditionsQuery() { // [START fs_multiple_cursor_conditions] + // [START firestore_query_cursor_start_at_field_value_multi] // Will return all Springfields Query query1 = db.collection("cities").orderBy("name").orderBy("state").startAt("Springfield"); // Will return "Springfield, Missouri" and "Springfield, Wisconsin" Query query2 = db.collection("cities").orderBy("name").orderBy("state").startAt("Springfield", "Missouri"); + // [END firestore_query_cursor_start_at_field_value_multi] // [END fs_multiple_cursor_conditions] } @@ -380,12 +416,14 @@ void createMultipleCursorConditionsQuery() { Query createStartAtSnapshotQueryCursor() throws InterruptedException, ExecutionException, TimeoutException { // [START fs_document_snapshot_cursor] + // [START firestore_query_cursor_start_at_document] // Fetch the snapshot with an API call, waiting for a maximum of 30 seconds for a result. ApiFuture future = db.collection("cities").document("SF").get(); DocumentSnapshot snapshot = future.get(30, TimeUnit.SECONDS); // Construct the query Query query = db.collection("cities").orderBy("population").startAt(snapshot); + // [END firestore_query_cursor_start_at_document] // [END fs_document_snapshot_cursor] return query; } @@ -393,6 +431,7 @@ Query createStartAtSnapshotQueryCursor() /** Example of a paginated query. */ List paginateCursor() throws InterruptedException, ExecutionException, TimeoutException { // [START fs_paginate_cursor] + // [START firestore_query_cursor_pagination] // Construct query for first 25 cities, ordered by population. CollectionReference cities = db.collection("cities"); Query firstPage = cities.orderBy("population").limit(25); @@ -407,6 +446,7 @@ List paginateCursor() throws InterruptedException, ExecutionException, Ti future = secondPage.get(); docs = future.get(30, TimeUnit.SECONDS).getDocuments(); + // [END firestore_query_cursor_pagination] // [END fs_paginate_cursor] return Arrays.asList(firstPage, secondPage); } @@ -415,6 +455,7 @@ void collectionGroupQuery() throws ExecutionException, InterruptedException { // CHECKSTYLE OFF: Indentation // CHECKSTYLE OFF: RightCurlyAlone // [START fs_collection_group_query_data_setup] + // [START firestore_query_collection_group_dataset] CollectionReference cities = db.collection("cities"); final List> futures = @@ -530,14 +571,17 @@ void collectionGroupQuery() throws ExecutionException, InterruptedException { } })); final List landmarks = ApiFutures.allAsList(futures).get(); + // [END firestore_query_collection_group_dataset] // [END fs_collection_group_query_data_setup] // [START fs_collection_group_query] + // [START firestore_query_collection_group_filter_eq] final Query museums = db.collectionGroup("landmarks").whereEqualTo("type", "museum"); final ApiFuture querySnapshot = museums.get(); for (DocumentSnapshot document : querySnapshot.get().getDocuments()) { System.out.println(document.getId()); } + // [END firestore_query_collection_group_filter_eq] // [END fs_collection_group_query] // CHECKSTYLE ON: RightCurlyAlone // CHECKSTYLE ON: Indentation @@ -545,48 +589,58 @@ void collectionGroupQuery() throws ExecutionException, InterruptedException { public Query arrayContainsAnyQueries() { // [START fs_query_filter_array_contains_any] + // [START firestore_query_filter_array_contains_any] CollectionReference citiesRef = db.collection("cities"); Query query = citiesRef.whereArrayContainsAny("regions", Arrays.asList("west_coast", "east_coast")); + // [END firestore_query_filter_array_contains_any] // [END fs_query_filter_array_contains_any] return query; } public Query inQueryWithoutArray() { // [START fs_query_filter_in] + // [START firestore_query_filter_in] CollectionReference citiesRef = db.collection("cities"); Query query = citiesRef.whereIn("country", Arrays.asList("USA", "Japan")); + // [END firestore_query_filter_in] // [END fs_query_filter_in] return query; } public Query inQueryWithArray() { // [START fs_query_filter_in_with_array] + // [START firestore_query_filter_in_with_array] CollectionReference citiesRef = db.collection("cities"); Query query = citiesRef.whereIn( "regions", Arrays.asList(Arrays.asList("west_coast"), Arrays.asList("east_coast"))); + // [END firestore_query_filter_in_with_array] // [END fs_query_filter_in_with_array] return query; } Query notEqualsQuery() { // [START fs_query_not_equals] + // [START firestore_query_filter_not_eq] CollectionReference citiesRef = db.collection("cities"); Query query = citiesRef.whereNotEqualTo("capital", false); + // [END firestore_query_filter_not_eq] // [END fs_query_not_equals] return query; } Query filterNotIn() { // [START fs_filter_not_in] + // [START firestore_query_filter_not_in] CollectionReference citiesRef = db.collection("cities"); Query query = citiesRef.whereNotIn("country", Arrays.asList("USA", "Japan")); + // [END firestore_query_filter_not_in] // [END fs_filter_not_in] return query; } diff --git a/samples/snippets/src/main/java/com/example/firestore/snippets/References.java b/samples/snippets/src/main/java/com/example/firestore/snippets/References.java index afa2d7506..ea28e6c8b 100644 --- a/samples/snippets/src/main/java/com/example/firestore/snippets/References.java +++ b/samples/snippets/src/main/java/com/example/firestore/snippets/References.java @@ -36,8 +36,10 @@ public References(Firestore db) { */ public CollectionReference getACollectionRef() { // [START fs_collection_ref] + // [START firestore_data_reference_collection] // Reference to the collection "users" CollectionReference collection = db.collection("users"); + // [END firestore_data_reference_collection] // [END fs_collection_ref] return collection; } @@ -49,8 +51,10 @@ public CollectionReference getACollectionRef() { */ public DocumentReference getADocumentRef() { // [START fs_document_ref] + // [START firestore_data_reference_document] // Reference to a document with id "alovelace" in the collection "users" DocumentReference document = db.collection("users").document("alovelace"); + // [END firestore_data_reference_document] // [END fs_document_ref] return document; } @@ -62,8 +66,10 @@ public DocumentReference getADocumentRef() { */ public DocumentReference getADocumentRefUsingPath() { // [START fs_document_path_ref] + // [START firestore_data_reference_document_path] // Reference to a document with id "alovelace" in the collection "users" DocumentReference document = db.document("users/alovelace"); + // [END firestore_data_reference_document_path] // [END fs_document_path_ref] return document; } @@ -75,9 +81,11 @@ public DocumentReference getADocumentRefUsingPath() { */ public DocumentReference getASubCollectionDocumentRef() { // [START fs_subcollection_ref] + // [START firestore_data_reference_subcollection] // Reference to a document in subcollection "messages" DocumentReference document = db.collection("rooms").document("roomA").collection("messages").document("message1"); + // [END firestore_data_reference_subcollection] // [END fs_subcollection_ref] return document; } diff --git a/samples/snippets/src/main/java/com/example/firestore/snippets/RetrieveDataSnippets.java b/samples/snippets/src/main/java/com/example/firestore/snippets/RetrieveDataSnippets.java index d89a1fb6d..3e9afb137 100644 --- a/samples/snippets/src/main/java/com/example/firestore/snippets/RetrieveDataSnippets.java +++ b/samples/snippets/src/main/java/com/example/firestore/snippets/RetrieveDataSnippets.java @@ -43,6 +43,7 @@ public class RetrieveDataSnippets { /** Create cities collection and add sample documents. */ void prepareExamples() throws Exception { // [START fs_retrieve_create_examples] + // [START firestore_data_get_dataset] CollectionReference cities = db.collection("cities"); List> futures = new ArrayList<>(); futures.add(cities.document("SF").set(new City("San Francisco", "CA", "USA", false, 860000L, @@ -57,6 +58,7 @@ void prepareExamples() throws Exception { Arrays.asList("jingjinji", "hebei")))); // (optional) block on operation ApiFutures.allAsList(futures).get(); + // [END firestore_data_get_dataset] // [END fs_retrieve_create_examples] } @@ -67,6 +69,7 @@ void prepareExamples() throws Exception { */ public Map getDocumentAsMap() throws Exception { // [START fs_get_doc_as_map] + // [START firestore_data_get_as_map] DocumentReference docRef = db.collection("cities").document("SF"); // asynchronously retrieve the document ApiFuture future = docRef.get(); @@ -78,6 +81,7 @@ public Map getDocumentAsMap() throws Exception { } else { System.out.println("No such document!"); } + // [END firestore_data_get_as_map] // [END fs_get_doc_as_map] return (document.exists()) ? document.getData() : null; } @@ -89,6 +93,7 @@ public Map getDocumentAsMap() throws Exception { */ public City getDocumentAsEntity() throws Exception { // [START fs_get_doc_as_entity] + // [START firestore_data_get_as_custom_type] DocumentReference docRef = db.collection("cities").document("BJ"); // asynchronously retrieve the document ApiFuture future = docRef.get(); @@ -102,6 +107,7 @@ public City getDocumentAsEntity() throws Exception { } else { System.out.println("No such document!"); } + // [END firestore_data_get_as_custom_type] // [END fs_get_doc_as_entity] return city; } @@ -113,6 +119,7 @@ public City getDocumentAsEntity() throws Exception { */ public List getQueryResults() throws Exception { // [START fs_get_multiple_docs] + // [START firestore_data_query] //asynchronously retrieve multiple documents ApiFuture future = db.collection("cities").whereEqualTo("capital", true).get(); @@ -121,6 +128,7 @@ public List getQueryResults() throws Exception { for (DocumentSnapshot document : documents) { System.out.println(document.getId() + " => " + document.toObject(City.class)); } + // [END firestore_data_query] // [END fs_get_multiple_docs] return documents; } @@ -132,6 +140,7 @@ public List getQueryResults() throws Exception { */ public List getAllDocuments() throws Exception { // [START fs_get_all_docs] + // [START firestore_data_get_all_documents] //asynchronously retrieve all documents ApiFuture future = db.collection("cities").get(); // future.get() blocks on response @@ -139,6 +148,7 @@ public List getAllDocuments() throws Exception { for (QueryDocumentSnapshot document : documents) { System.out.println(document.getId() + " => " + document.toObject(City.class)); } + // [END firestore_data_get_all_documents] // [END fs_get_all_docs] return documents; } @@ -150,12 +160,14 @@ public List getAllDocuments() throws Exception { */ public Iterable listCollections() throws Exception { // [START fs_get_collections] + // [START firestore_data_get_sub_collections] Iterable collections = db.collection("cities").document("SF").listCollections(); for (CollectionReference collRef : collections) { System.out.println("Found subcollection with id: " + collRef.getId()); } + // [END firestore_data_get_sub_collections] // [END fs_get_collections] return collections; } diff --git a/samples/snippets/src/main/java/com/example/firestore/snippets/model/City.java b/samples/snippets/src/main/java/com/example/firestore/snippets/model/City.java index 48a41145a..e48400f5f 100644 --- a/samples/snippets/src/main/java/com/example/firestore/snippets/model/City.java +++ b/samples/snippets/src/main/java/com/example/firestore/snippets/model/City.java @@ -30,6 +30,7 @@ public class City { private List regions; // [START fs_class_definition] + // [START firestore_data_custom_type_definition] public City() { // Must have a public no-argument constructor } @@ -44,6 +45,7 @@ public City(String name, String state, String country, this.population = population; this.regions = regions; } + // [END firestore_data_custom_type_definition] // [END fs_class_definition] public City(String name) {