com.google.cloud.firestore.DocumentReference Java Examples

The following examples show how to use com.google.cloud.firestore.DocumentReference. 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: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Update array fields in a document. **/
void updateDocumentArray() throws Exception {
  // [START fs_update_document_array]
  DocumentReference washingtonRef = db.collection("cities").document("DC");

  // Atomically add a new region to the "regions" array field.
  ApiFuture<WriteResult> arrayUnion = washingtonRef.update("regions",
      FieldValue.arrayUnion("greater_virginia"));
  System.out.println("Update time : " + arrayUnion.get());

  // Atomically remove a region from the "regions" array field.
  ApiFuture<WriteResult> arrayRm = washingtonRef.update("regions",
      FieldValue.arrayRemove("east_coast"));
  System.out.println("Update time : " + arrayRm.get());
  // [END fs_update_document_array]
}
 
Example #2
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Run a simple transaction to perform a field value increment.
 *
 * @return transaction future
 */
ApiFuture<Void> runSimpleTransaction() throws Exception {
  // [START fs_run_simple_transaction]
  // Initialize doc
  final DocumentReference docRef = db.collection("cities").document("SF");
  City city = new City("SF");
  city.setCountry("USA");
  city.setPopulation(860000L);
  docRef.set(city).get();

  // run an asynchronous transaction
  ApiFuture<Void> futureTransaction = db.runTransaction(transaction -> {
    // retrieve document and increment population field
    DocumentSnapshot snapshot = transaction.get(docRef).get();
    long oldPopulation = snapshot.getLong("population");
    transaction.update(docRef, "population", oldPopulation + 1);
    return null;
  });
  // block on transaction operation using transaction.get()
  // [END fs_run_simple_transaction]
  return futureTransaction;
}
 
Example #3
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Partially update fields of a document using a map (field => value). */
void updateUsingMap() throws Exception {
  db.collection("cities").document("DC").set(new City("Washington D.C.")).get();
  // [START fs_update_doc_map]
  // update multiple fields using a map
  DocumentReference docRef = db.collection("cities").document("DC");

  Map<String, Object> updates = new HashMap<>();
  updates.put("name", "Washington D.C.");
  updates.put("country", "USA");
  updates.put("capital", true);

  //asynchronously update doc
  ApiFuture<WriteResult> writeResult = docRef.update(updates);
  // ...
  System.out.println("Update time : " + writeResult.get().getUpdateTime());
  // [END fs_update_doc_map]
}
 
Example #4
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Return information from a conditional transaction.
 *
 *
 * @param population : set initial population.
 */
String returnInfoFromTransaction(long population) throws Exception {
  Map<String, Object> map = new HashMap<>();
  map.put("population", population);
  // Block until transaction is complete is using transaction.get()
  db.collection("cities").document("SF").set(map).get();
  // [START fs_return_info_transaction]
  final DocumentReference docRef = db.collection("cities").document("SF");
  ApiFuture<String> futureTransaction = db.runTransaction(transaction -> {
    DocumentSnapshot snapshot = transaction.get(docRef).get();
    Long newPopulation = snapshot.getLong("population") + 1;
    // conditionally update based on current population
    if (newPopulation <= 1000000L) {
      transaction.update(docRef, "population", newPopulation);
      return "Population increased to " + newPopulation;
    } else {
      throw new Exception("Sorry! Population is too big.");
    }
  });
  // Print information retrieved from transaction
  System.out.println(futureTransaction.get());
  // [END fs_return_info_transaction]
  return futureTransaction.get();
}
 
Example #5
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Add data to a document after generating the document id.
 *
 * @return auto generated id
 */
String addDocumentDataAfterAutoGeneratingId() throws Exception {
  City data = new City();

  // [START fs_add_doc_data_after_auto_id]
  // 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> writeResult = addedDocRef.set(data);
  // [END fs_add_doc_data_after_auto_id]

  // writeResult.get() blocks on operation
  System.out.println("Update time : " + writeResult.get().getUpdateTime());
  return addedDocRef.getId();
}
 
Example #6
Source File: FirestoreClientIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testFirestoreAccess() throws Exception {
  Firestore firestore = FirestoreClient.getFirestore(IntegrationTestUtils.ensureDefaultApp());
  DocumentReference reference = firestore.collection("cities").document("Mountain View");
  ImmutableMap<String, Object> expected = ImmutableMap.<String, Object>of(
      "name", "Mountain View",
      "country", "USA",
      "population", 77846L,
      "capital", false
  );
  WriteResult result = reference.set(expected).get();
  assertNotNull(result);

  Map<String, Object> data = reference.get().get().getData();
  assertEquals(expected.size(), data.size());
  for (Map.Entry<String, Object> entry : expected.entrySet()) {
    assertEquals(entry.getValue(), data.get(entry.getKey()));
  }

  reference.delete().get();
  assertFalse(reference.get().get().exists());
}
 
Example #7
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 #8
Source File: FirestoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public String createBook(Book book) {
  String id = UUID.randomUUID().toString();
  DocumentReference document = booksCollection.document(id);
  Map<String, Object> data = Maps.newHashMap();

  data.put(Book.AUTHOR, book.getAuthor());
  data.put(Book.DESCRIPTION, book.getDescription());
  data.put(Book.PUBLISHED_DATE, book.getPublishedDate());
  data.put(Book.TITLE, book.getTitle());
  data.put(Book.IMAGE_URL, book.getImageUrl());
  data.put(Book.CREATED_BY, book.getCreatedBy());
  data.put(Book.CREATED_BY_ID, book.getCreatedById());
  try {
    document.set(data).get();
  } catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
  }

  return id;
}
 
Example #9
Source File: FirestoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public void updateBook(Book book) {
  DocumentReference document = booksCollection.document(book.getId());
  Map<String, Object> data = Maps.newHashMap();

  data.put(Book.AUTHOR, book.getAuthor());
  data.put(Book.DESCRIPTION, book.getDescription());
  data.put(Book.PUBLISHED_DATE, book.getPublishedDate());
  data.put(Book.TITLE, book.getTitle());
  data.put(Book.IMAGE_URL, book.getImageUrl());
  data.put(Book.CREATED_BY, book.getCreatedBy());
  data.put(Book.CREATED_BY_ID, book.getCreatedById());
  try {
    document.set(data).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 testAddDocAfterAutoGenId() throws Exception {
  String autoId = manageDataSnippets.addDocumentDataAfterAutoGeneratingId();
  City city = new City();
  DocumentReference docRef = db.collection("cities").document(autoId);
  assertTrue(Objects.equals(city, getDocumentDataAsCity(docRef)));
}
 
Example #11
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Write documents in a batch. */
void writeBatch() throws Exception {
  db.collection("cities").document("SF").set(new City()).get();
  db.collection("cities").document("LA").set(new City()).get();

  // [START fs_write_batch]
  // Get a new write batch
  WriteBatch batch = db.batch();

  // Set the value of 'NYC'
  DocumentReference nycRef = db.collection("cities").document("NYC");
  batch.set(nycRef, new City());

  // Update the population of 'SF'
  DocumentReference sfRef = db.collection("cities").document("SF");
  batch.update(sfRef, "population", 1000000L);

  // Delete the city 'LA'
  DocumentReference laRef = db.collection("cities").document("LA");
  batch.delete(laRef);

  // asynchronously commit the batch
  ApiFuture<List<WriteResult>> future = batch.commit();
  // ...
  // future.get() blocks on batch commit operation
  for (WriteResult result :future.get()) {
    System.out.println("Update time : " + result.getUpdateTime());
  }
  // [END fs_write_batch]
}
 
Example #12
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public void updateDocumentIncrement() throws ExecutionException, InterruptedException {
  final City city = new City();
  city.setPopulation(100L);
  db.collection("cities").document("DC").set(city).get();

  // [START fs_update_document_increment]
  DocumentReference washingtonRef = db.collection("cities").document("DC");

  // Atomically increment the population of the city by 50.
  final ApiFuture<WriteResult> updateFuture = washingtonRef
      .update("population", FieldValue.increment(50));
  // [END fs_update_document_increment]
  updateFuture.get();
}
 
Example #13
Source File: ListenDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Listen to a single document, returning data after the first snapshot.
 */
Map<String, Object> listenToDocument() throws Exception {
  final SettableApiFuture<Map<String, Object>> future = SettableApiFuture.create();

  // [START listen_to_document]
  DocumentReference docRef = db.collection("cities").document("SF");
  docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(@Nullable DocumentSnapshot snapshot,
                        @Nullable FirestoreException e) {
      if (e != null) {
        System.err.println("Listen failed: " + e);
        return;
      }

      if (snapshot != null && snapshot.exists()) {
        System.out.println("Current data: " + snapshot.getData());
      } else {
        System.out.print("Current data: null");
      }
      // [START_EXCLUDE silent]
      if (!future.isDone()) {
        future.set(snapshot.getData());
      }
      // [END_EXCLUDE]
    }
  });
  // [END listen_to_document]

  return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
 
Example #14
Source File: BaseIntegrationTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
protected Map<String, Object> getDocumentDataAsMap(DocumentReference docRef) throws Exception {
  DocumentSnapshot snapshot = docRef.get().get();
  if (!snapshot.exists()) {
    throw new RuntimeException("Document does not exist: " + docRef.getPath());
  }

  return snapshot.getData();
}
 
Example #15
Source File: ManageDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddDocWithAutoGenId() throws Exception {
  String autoId = manageDataSnippets.addDocumentDataWithAutoGeneratedId();
  City city = new City("Tokyo");
  city.setCountry("Japan");
  DocumentReference docRef = db.collection("cities").document(autoId);
  assertTrue(Objects.equals(city, getDocumentDataAsCity(docRef)));
}
 
Example #16
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Delete specific fields when updating a document. */
void deleteFields() throws Exception {
  City city = new City("Beijing");
  city.setCapital(true);
  db.collection("cities").document("BJ").set(city).get();

  // [START fs_delete_fields]
  DocumentReference docRef = db.collection("cities").document("BJ");
  Map<String, Object> updates = new HashMap<>();
  updates.put("capital", FieldValue.delete());
  // Update and delete the "capital" field in the document
  ApiFuture<WriteResult> writeResult = docRef.update(updates);
  System.out.println("Update time : " + writeResult.get());
  // [END fs_delete_fields]
}
 
Example #17
Source File: ManageDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateSimpleDocument() throws Exception {
  manageDataSnippets.updateSimpleDocument();
  DocumentReference docRef = db.collection("cities").document("DC");
  City city = new City("Washington D.C.");
  city.setCapital(true);
  assertTrue(Objects.equals(city, getDocumentDataAsCity(docRef)));
}
 
Example #18
Source File: ManageDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateUsingMap() throws Exception {
  manageDataSnippets.updateUsingMap();
  DocumentReference docRef = db.collection("cities").document("DC");
  City city = new City("Washington D.C.");
  city.setCapital(true);
  city.setCountry("USA");
  assertTrue(Objects.equals(city, getDocumentDataAsCity(docRef)));
}
 
Example #19
Source File: ManageDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateNestedFields() throws Exception {
  manageDataSnippets.updateNestedFields();
  DocumentReference docRef = db.collection("users").document("frank");

  DocumentSnapshot snapshot = getDocumentData(docRef);
  assertEquals((long) snapshot.getLong("age"), 13);
  assertEquals(snapshot.getString("favorites.color"), "Red");
  assertEquals(snapshot.getString("favorites.food"), "Pizza");
}
 
Example #20
Source File: ManageDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateServerTimestamp() throws Exception {
  manageDataSnippets.updateServerTimestamp();
  DocumentReference docRef = db.collection("objects").document("some-id");
  DocumentSnapshot data = getDocumentData(docRef);
  assertTrue(data.getDate("timestamp") instanceof Date);
}
 
Example #21
Source File: ManageDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateDocumentArray() throws Exception {
  manageDataSnippets.updateDocumentArray();
  DocumentReference docRef = db.collection("cities").document("DC");
  City city = getDocumentDataAsCity(docRef);
  assertTrue(city.getRegions().contains("greater_virginia"));
  assertTrue(!city.getRegions().contains("east_coast"));
}
 
Example #22
Source File: ManageDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteFields() throws Exception {
  manageDataSnippets.deleteFields();
  DocumentReference docRef = db.collection("cities").document("BJ");
  Map<String, Object> data = getDocumentDataAsMap(docRef);
  assertFalse(data.containsKey("capital"));
}
 
Example #23
Source File: ManageDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleTransaction() throws Exception {
  DocumentReference docRef = db.collection("cities").document("SF");
  ApiFuture<Void> future = manageDataSnippets.runSimpleTransaction();
  future.get();
  Map<String, Object> data = getDocumentDataAsMap(docRef);
  assertEquals(data.get("population"), 860000L + 1L);
}
 
Example #24
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 #25
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 #26
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 #27
Source File: FirestoreSampleApp.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private void writeDocumentFromMap() throws InterruptedException, java.util.concurrent.ExecutionException {
	DocumentReference docRef = this.firestore.collection("users").document("ada");
	// Add document data with id "ada" using a hashmap
	Map<String, Object> data = new HashMap<>();
	data.put("name", "Ada");
	data.put("phones", Arrays.asList(123, 456));

	// asynchronously write data
	ApiFuture<WriteResult> result = docRef.set(data);

	// result.get() blocks on response
	System.out.println("Update time: " + result.get().getUpdateTime());
}
 
Example #28
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 5 votes vote down vote up
public DocumentReference addProtoDocumentToCollection(String path, Message proto) {
  try {
    return addProtoDocumentToCollectionAsync(path, proto).get();
  } catch (ExecutionException | InterruptedException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #29
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Update document with server timestamp. */
void updateServerTimestamp() throws Exception {
  db.collection("objects").document("some-id").set(new HashMap<String, Object>()).get();

  // [START fs_update_server_timestamp]
  DocumentReference docRef = db.collection("objects").document("some-id");
  // Update the timestamp field with the value from the server
  ApiFuture<WriteResult> writeResult = docRef.update("timestamp", FieldValue.serverTimestamp());
  System.out.println("Update time : " + writeResult.get());
  // [END fs_update_server_timestamp]
}
 
Example #30
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 5 votes vote down vote up
public ApiFuture<DocumentReference> addProtoDocumentToCollectionAsync(
    String path, Message proto) {
  try {
    return getCollectionReference(path).add(encodeProto(proto));
  } catch (InvalidProtocolBufferException e) {
    throw new IllegalStateException(e);
  }
}