com.google.cloud.firestore.CollectionReference Java Examples

The following examples show how to use com.google.cloud.firestore.CollectionReference. 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: RetrieveDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSubcollections() throws Exception {
  // Add a landmark subcollection
  Map<String, String> data = new HashMap<>();
  data.put("foo", "bar");
  db.document("cities/SF/landmarks/example").set(data).get();

  Iterable<CollectionReference> collections =
      retrieveDataSnippets.listCollections();

  List<CollectionReference> collectionList = new ArrayList<>();
  for (CollectionReference collRef : collections) {
    collectionList.add(collRef);
  }

  assertEquals(collectionList.size(), 1);
  assertEquals(collectionList.get(0).getId(), "landmarks");
}
 
Example #2
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Example of a paginated query. */
List<Query> paginateCursor() throws InterruptedException, ExecutionException, TimeoutException {
  // [START fs_paginate_cursor]
  // Construct query for first 25 cities, ordered by population.
  CollectionReference cities = db.collection("cities");
  Query firstPage = cities.orderBy("population").limit(25);

  // Wait for the results of the API call, waiting for a maximum of 30 seconds for a result.
  ApiFuture<QuerySnapshot> future = firstPage.get();
  List<QueryDocumentSnapshot> docs = future.get(30, TimeUnit.SECONDS).getDocuments();

  // Construct query for the next 25 cities.
  QueryDocumentSnapshot lastDoc = docs.get(docs.size() - 1);
  Query secondPage = cities.orderBy("population").startAfter(lastDoc).limit(25);

  future = secondPage.get();
  docs = future.get(30, TimeUnit.SECONDS).getDocuments();
  // [END fs_paginate_cursor]
  return Arrays.asList(firstPage, secondPage);
}
 
Example #3
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates queries with simple where clauses.
 *
 * @return queries
 */
List<Query> createSimpleQueries() {
  List<Query> querys = new ArrayList<>();
  CollectionReference cities = db.collection("cities");

  // [START fs_simple_queries]
  Query stateQuery = cities.whereEqualTo("state", "CA");
  Query populationQuery = cities.whereLessThan("population", 1000000L);
  Query nameQuery = cities.whereGreaterThanOrEqualTo("name", "San Francisco");
  // [END fs_simple_queries]

  querys.add(stateQuery);
  querys.add(populationQuery);
  querys.add(nameQuery);
  return querys;
}
 
Example #4
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a sample query.
 *
 * @return query
 */
Query createAQueryAlternate() throws Exception {
  // [START fs_create_query_country]
  // Create a reference to the cities collection
  CollectionReference cities = db.collection("cities");
  // Create a query against the collection.
  Query query = cities.whereEqualTo("state", "CA");
  // retrieve  query results asynchronously using query.get()
  ApiFuture<QuerySnapshot> querySnapshot = query.get();

  for (DocumentSnapshot document : querySnapshot.get().getDocuments()) {
    System.out.println(document.getId());
  }
  // [END fs_create_query_country]
  return query;
}
 
Example #5
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a sample query.
 *
 * @return query
 */
Query createAQuery() throws Exception {
  // [START fs_create_query]
  // Create a reference to the cities collection
  CollectionReference cities = db.collection("cities");
  // Create a query against the collection.
  Query query = cities.whereEqualTo("capital", true);
  // retrieve  query results asynchronously using query.get()
  ApiFuture<QuerySnapshot> querySnapshot = query.get();

  for (DocumentSnapshot document : querySnapshot.get().getDocuments()) {
    System.out.println(document.getId());
  }
  // [END fs_create_query]
  return query;
}
 
Example #6
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** 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.
 */
void deleteCollection(CollectionReference collection, int batchSize) {
  try {
    // retrieve a small batch of documents to avoid out-of-memory errors
    ApiFuture<QuerySnapshot> future = collection.limit(batchSize).get();
    int deleted = 0;
    // future.get() blocks on document retrieval
    List<QueryDocumentSnapshot> documents = future.get().getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      document.getReference().delete();
      ++deleted;
    }
    if (deleted >= batchSize) {
      // retrieve and delete another batch
      deleteCollection(collection, batchSize);
    }
  } catch (Exception e) {
    System.err.println("Error deleting collection : " + e.getMessage());
  }
}
 
Example #7
Source File: RetrieveDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Create cities collection and add sample documents. */
void prepareExamples() throws Exception {
  // [START fs_retrieve_create_examples]
  CollectionReference cities = db.collection("cities");
  List<ApiFuture<WriteResult>> futures = new ArrayList<>();
  futures.add(cities.document("SF").set(new City("San Francisco", "CA", "USA", false, 860000L,
      Arrays.asList("west_coast", "norcal"))));
  futures.add(cities.document("LA").set(new City("Los Angeles", "CA", "USA", false, 3900000L,
      Arrays.asList("west_coast", "socal"))));
  futures.add(cities.document("DC").set(new City("Washington D.C.", null, "USA", true, 680000L,
      Arrays.asList("east_coast"))));
  futures.add(cities.document("TOK").set(new City("Tokyo", null, "Japan", true, 9000000L,
      Arrays.asList("kanto", "honshu"))));
  futures.add(cities.document("BJ").set(new City("Beijing", null, "China", true, 21500000L,
      Arrays.asList("jingjinji", "hebei"))));
  // (optional) block on operation
  ApiFutures.allAsList(futures).get();
  // [END fs_retrieve_create_examples]
}
 
Example #8
Source File: TranslateServlet.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  Firestore firestore = (Firestore) this.getServletContext().getAttribute("firestore");
  CollectionReference translations = firestore.collection("translations");
  QuerySnapshot snapshot;
  try {
    snapshot = translations.limit(10).get().get();
  } catch (InterruptedException | ExecutionException e) {
    throw new ServletException("Exception retrieving documents from Firestore.", e);
  }
  List<TranslateMessage> translateMessages = Lists.newArrayList();
  List<QueryDocumentSnapshot> documents = Lists.newArrayList(snapshot.getDocuments());
  documents.sort(Comparator.comparing(DocumentSnapshot::getCreateTime));

  for (DocumentSnapshot document : Lists.reverse(documents)) {
    String encoded = gson.toJson(document.getData());
    TranslateMessage message = gson.fromJson(encoded, TranslateMessage.class);
    message.setData(decode(message.getData()));
    translateMessages.add(message);
  }
  req.setAttribute("messages", translateMessages);
  req.setAttribute("page", "list");
  req.getRequestDispatcher("/base.jsp").forward(req, resp);
}
 
Example #9
Source File: FirestoreSampleApp.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private void removeDocuments() {
	//Warning: Deleting a document does not delete its subcollections!
	//
	//If you want to delete documents in subcollections when deleting a document, you must do so manually.
	//See https://firebase.google.com/docs/firestore/manage-data/delete-data#collections
	CollectionReference users = this.firestore.collection("users");
	Iterable<DocumentReference> documentReferences = users.listDocuments();
	documentReferences.forEach(documentReference -> {
		System.out.println("removing: " + documentReference.getId());
		try {
			documentReference.delete().get();
		}
		catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	});
}
 
Example #10
Source File: ManageDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteBatchIsSuccessful() throws Exception {
  manageDataSnippets.writeBatch();
  CollectionReference collection = db.collection("cities");
  ApiFuture<DocumentSnapshot> document = collection.document("NYC").get();
  assertTrue(document.get().exists());
  DocumentReference documentReference = collection.document("SF");
  Map<String, Object> data = getDocumentDataAsMap(documentReference);
  assertTrue(data.containsKey("population"));
  document = collection.document("LA").get();
  assertFalse(document.get().exists());
}
 
Example #11
Source File: ManageDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateDocumentIncrementSuccessful() throws Exception {
  manageDataSnippets.updateDocumentIncrement();
  CollectionReference collection = db.collection("cities");
  DocumentReference documentReference = collection.document("DC");
  final DocumentSnapshot data = documentReference.get().get();
  assertTrue(data.contains("population"));
  assertEquals((Long) 150L, data.getLong("population"));
}
 
Example #12
Source File: References.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Return a reference to collection.
 *
 * @return collection reference
 */
public CollectionReference getACollectionRef() {
  // [START fs_collection_ref]
  // Reference to the collection "users"
  CollectionReference collection = db.collection("users");
  // [END fs_collection_ref]
  return collection;
}
 
Example #13
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public Query inQueryWithArray() {
  // [START fs_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 fs_query_filter_in_with_array]
  return query;
}
 
Example #14
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public Query inQueryWithoutArray() {
  // [START fs_query_filter_in]
  CollectionReference citiesRef = db.collection("cities");

  Query query = citiesRef.whereIn("country", Arrays.asList("USA", "Japan"));
  // [END fs_query_filter_in]
  return query;
}
 
Example #15
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public Query arrayContainsAnyQueries() {
  // [START fs_query_filter_array_contains_any]
  CollectionReference citiesRef = db.collection("cities");

  Query query =
      citiesRef.whereArrayContainsAny("regions", Arrays.asList("west_coast", "east_coast"));
  // [END fs_query_filter_array_contains_any]
  return query;
}
 
Example #16
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a query that combines order by with limitToLast.
 *
 * @return query
 */
Query createOrderByNameWithLimitToLastQuery() {
  CollectionReference cities = db.collection("cities");
  // [START fs_order_by_name_limit_query]
  Query query = cities.orderBy("name").limitToLast(3);
  // [END fs_order_by_name_limit_query]
  return query;
}
 
Example #17
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Create a query defining the start point of a query.
 *
 * @return query
 */
Query createEndAtFieldQueryCursor() {
  CollectionReference cities = db.collection("cities");
  // [START fs_end_at_field_query_cursor]
  Query query = cities.orderBy("population").endAt(4921000L);
  // [END fs_end_at_field_query_cursor]
  return query;
}
 
Example #18
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Create a query defining the start point of a query.
 *
 * @return query
 */
Query createStartAtFieldQueryCursor() {
  CollectionReference cities = db.collection("cities");
  // [START fs_start_at_field_query_cursor]
  Query query = cities.orderBy("population").startAt(4921000L);
  // [END fs_start_at_field_query_cursor]
  return query;
}
 
Example #19
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance of an invalid range combined with order. Violates the constraint that range
 * and order by are required to be on the same field.
 *
 * @return query
 */
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]
  Query query = cities.whereGreaterThan("population", 2500000L).orderBy("country");
  // [END fs_invalid_range_order_by_query]
  return query;
}
 
Example #20
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a query using a range where clause with order by. Order by must be based on the same
 * field as the range clause.
 *
 * @return query
 */
Query createRangeWithOrderByQuery() {
  CollectionReference cities = db.collection("cities");
  // [START fs_range_order_by_query]
  Query query = cities.whereGreaterThan("population", 2500000L).orderBy("population");
  // [END fs_range_order_by_query]
  return query;
}
 
Example #21
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a query that combines where clause with order by and limit operator.
 *
 * @return query
 */
Query createWhereWithOrderByAndLimitQuery() {
  CollectionReference cities = db.collection("cities");
  // [START fs_where_order_by_limit_query]
  Query query = cities.whereGreaterThan("population", 2500000L).orderBy("population").limit(2);
  // [END fs_where_order_by_limit_query]
  return query;
}
 
Example #22
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a query that combines order by in descending order with the limit operator.
 *
 * @return query
 */
Query createOrderByNameDescWithLimitQuery() {
  CollectionReference cities = db.collection("cities");
  // [START fs_order_by_name_desc_limit_query]
  Query query = cities.orderBy("name", Direction.DESCENDING).limit(3);
  // [END fs_order_by_name_desc_limit_query]
  return query;
}
 
Example #23
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a query that orders by country and population(descending).
 *
 * @return query
 */
Query createOrderByCountryAndPopulation() {
  CollectionReference cities = db.collection("cities");
  // [START fs_order_by_country_population]
  Query query = cities.orderBy("state").orderBy("population", Direction.DESCENDING);
  // [END fs_order_by_country_population]
  return query;
}
 
Example #24
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 5 votes vote down vote up
private CollectionReference getCollectionReference(String[] parts, int length) {
  DocumentReference docRef;
  CollectionReference collectionRef = client.collection(parts[0]);
  for (int i = 1; i < length; i += 2) {
    docRef = collectionRef.document(parts[i]);
    collectionRef = docRef.collection(parts[i + 1]);
  }
  return collectionRef;
}
 
Example #25
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a query that combines order by with limit.
 *
 * @return query
 */
Query createOrderByNameWithLimitQuery() {
  CollectionReference cities = db.collection("cities");
  // [START fs_order_by_name_limit_query]
  Query query = cities.orderBy("name").limit(3);
  // [END fs_order_by_name_limit_query]
  return query;
}
 
Example #26
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * An instance of an invalid range query : range operators are limited to a single field.
 *
 * @return query
 */
Query createInvalidRangeQuery() {
  CollectionReference cities = db.collection("cities");
  // Violates constraint : range operators are limited to a single field
  // [START fs_invalid_range_query]
  Query invalidRangeQuery =
      cities.whereGreaterThanOrEqualTo("state", "CA").whereGreaterThan("population", 100000);
  // [END fs_invalid_range_query]
  return invalidRangeQuery;
}
 
Example #27
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * An instance of a valid range/inequality query : range operators are limited to a single field.
 *
 * @return query
 */
Query createRangeQuery() {
  CollectionReference cities = db.collection("cities");
  // [START fs_range_query]
  Query validQuery1 =
      cities.whereGreaterThanOrEqualTo("state", "CA").whereLessThanOrEqualTo("state", "IN");
  Query validQuery2 = cities.whereEqualTo("state", "CA").whereGreaterThan("population", 1000000);
  // [END fs_range_query]
  return validQuery1;
}
 
Example #28
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * An instance of a currently unsupported chained query: equality with inequality. NOTE : Requires
 * support for creation of composite indices.
 *
 * @return query
 */
Query createCompositeIndexChainedQuery() {
  CollectionReference cities = db.collection("cities");
  // [START fs_composite_index_chained_query]
  Query chainedQuery2 = cities.whereEqualTo("state", "CA").whereLessThan("population", 1000000L);
  // [END fs_composite_index_chained_query]
  return chainedQuery2;
}
 
Example #29
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates chained where clauses.
 *
 * <p>Note : equality and inequality clauses over multiple fields cannot be chained.
 *
 * @return query
 */
Query createChainedQuery() {
  CollectionReference cities = db.collection("cities");
  // [START fs_chained_query]
  Query chainedQuery1 = cities.whereEqualTo("state", "CO").whereEqualTo("name", "Denver");
  // [END fs_chained_query]
  return chainedQuery1;
}
 
Example #30
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a query based on array containment.
 *
 * @return query
 */
Query createArrayQuery() {
  // [START fs_array_contains_filter]
  CollectionReference citiesRef = db.collection("cities");
  Query westCoastQuery = citiesRef.whereArrayContains("regions", "west_coast");
  // [END fs_array_contains_filter]

  return westCoastQuery;
}