com.google.cloud.firestore.QuerySnapshot Java Examples

The following examples show how to use com.google.cloud.firestore.QuerySnapshot. 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: MyDataStore.java    From smart-home-java with Apache License 2.0 6 votes vote down vote up
public String getUserId(String token) throws ExecutionException, InterruptedException {
  if (token == null) {
    token = "Bearer 123access";
  }
  ApiFuture<QuerySnapshot> userQuery =
      database.collection("users").whereEqualTo("fakeAccessToken", token.substring(7)).get();
  QuerySnapshot usersSnapshot = userQuery.get();
  List<QueryDocumentSnapshot> users = usersSnapshot.getDocuments();

  DocumentSnapshot user;
  try {
    user = users.get(0);
  } catch (Exception e) {
    LOGGER.error("no user found!");
    throw e;
  }

  return user.getId();
}
 
Example #2
Source File: FirestoreSessionFilter.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void init(FilterConfig config) throws ServletException {
  // Initialize local copy of datastore session variables.
  firestore = FirestoreOptions.getDefaultInstance().getService();
  sessions = firestore.collection("sessions");

  try {
    // Delete all sessions unmodified for over two days.
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.add(Calendar.HOUR, -48);
    Date twoDaysAgo = Calendar.getInstance().getTime();
    QuerySnapshot sessionDocs =
        sessions.whereLessThan("lastModified", dtf.format(twoDaysAgo)).get().get();
    for (QueryDocumentSnapshot snapshot : sessionDocs.getDocuments()) {
      snapshot.getReference().delete();
    }
  } catch (InterruptedException | ExecutionException e) {
    throw new ServletException("Exception initializing FirestoreSessionFilter.", e);
  }
}
 
Example #3
Source File: ListenDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Demonstrate how to handle listening errors.
 */
void listenErrors() {
  // [START listen_errors]
  db.collection("cities")
      .addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot snapshots,
                            @Nullable FirestoreException e) {
          if (e != null) {
            System.err.println("Listen failed: " + e);
            return;
          }

          for (DocumentChange dc : snapshots.getDocumentChanges()) {
            if (dc.getType() == Type.ADDED) {
              System.out.println("New city: " + dc.getDocument().getData());
            }
          }
        }
      });
  // [END listen_errors]
}
 
Example #4
Source File: ListenDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Demonstrate how to detach an event listener.
 */
void detachListener() {
  // [START detach_errors]
  Query query = db.collection("cities");
  ListenerRegistration registration = query.addSnapshotListener(
      new EventListener<QuerySnapshot>() {
        // [START_EXCLUDE]
        @Override
        public void onEvent(@Nullable QuerySnapshot snapshots,
                            @Nullable FirestoreException e) {

        }
        // [END_EXCLUDE]
      });

  // ...

  // Stop listening to changes
  registration.remove();
  // [END detach_errors]
}
 
Example #5
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 #6
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 #7
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 #8
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 #9
Source File: Quickstart.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
void retrieveAllDocuments() throws Exception {
  // [START fs_get_all]
  // asynchronously retrieve all users
  ApiFuture<QuerySnapshot> query = db.collection("users").get();
  // ...
  // query.get() blocks on response
  QuerySnapshot querySnapshot = query.get();
  List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
  for (QueryDocumentSnapshot document : documents) {
    System.out.println("User: " + document.getId());
    System.out.println("First: " + document.getString("first"));
    if (document.contains("middle")) {
      System.out.println("Middle: " + document.getString("middle"));
    }
    System.out.println("Last: " + document.getString("last"));
    System.out.println("Born: " + document.getLong("born"));
  }
  // [END fs_get_all]
}
 
Example #10
Source File: Quickstart.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
void runAQuery() throws Exception {
  // [START fs_add_query]
  // asynchronously query for all users born before 1900
  ApiFuture<QuerySnapshot> query =
      db.collection("users").whereLessThan("born", 1900).get();
  // ...
  // query.get() blocks on response
  QuerySnapshot querySnapshot = query.get();
  List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
  for (QueryDocumentSnapshot document : documents) {
    System.out.println("User: " + document.getId());
    System.out.println("First: " + document.getString("first"));
    if (document.contains("middle")) {
      System.out.println("Middle: " + document.getString("middle"));
    }
    System.out.println("Last: " + document.getString("last"));
    System.out.println("Born: " + document.getLong("born"));
  }
  // [END fs_add_query]
}
 
Example #11
Source File: FirestoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooksByUser(String userId, String startTitle) {
  Query booksQuery =
      booksCollection.orderBy("title").whereEqualTo(Book.CREATED_BY_ID, userId).limit(10);
  if (startTitle != null) {
    booksQuery = booksQuery.startAfter(startTitle);
  }
  try {
    QuerySnapshot snapshot = booksQuery.get().get();
    List<Book> results = documentsToBooks(snapshot.getDocuments());
    String newCursor = null;
    if (results.size() > 0) {
      newCursor = results.get(results.size() - 1).getTitle();
    }
    return new Result<>(results, newCursor);
  } catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
  }
  return new Result<>(Lists.newArrayList(), null);
}
 
Example #12
Source File: FirestoreDao.java    From getting-started-java with Apache License 2.0 6 votes vote down vote up
@Override
public Result<Book> listBooks(String startTitle) {
  Query booksQuery = booksCollection.orderBy("title").limit(10);
  if (startTitle != null) {
    booksQuery = booksQuery.startAfter(startTitle);
  }
  try {
    QuerySnapshot snapshot = booksQuery.get().get();
    List<Book> results = documentsToBooks(snapshot.getDocuments());
    String newCursor = null;
    if (results.size() > 0) {
      newCursor = results.get(results.size() - 1).getTitle();
    }
    return new Result<>(results, newCursor);
  } catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
  }
  return new Result<>(Lists.newArrayList(), null);
}
 
Example #13
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 #14
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 6 votes vote down vote up
public void addCollectionListener(
    String path, Message.Builder builder, ProtoEventListener listener) {
  getCollectionReference(path)
      .addSnapshotListener(
          new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(
                @Nullable QuerySnapshot querySnapshot, @Nullable FirestoreException e) {
              if (e != null) {
                listener.onEvent(null, e);
                return;
              }
              try {
                listener.onEvent(new ProtoQuerySnapshot(querySnapshot, builder), null);
              } catch (InvalidProtocolBufferException e2) {
                listener.onEvent(null, new IllegalArgumentException(e2));
              }
            }
          });
}
 
Example #15
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 6 votes vote down vote up
public MessageWithId getDocumentFromCollection(
    String path, Message.Builder builder, boolean shouldRemove) {
  try {
    QuerySnapshot querySnapshot = getCollectionReference(path).limit(1).get().get();
    if (querySnapshot.isEmpty()) {
      return null;
    }
    QueryDocumentSnapshot queryDocumentSnapshot = querySnapshot.getDocuments().get(0);
    MessageWithId result =
        MessageWithId.create(
            queryDocumentSnapshot.getId(), parseProto(queryDocumentSnapshot, builder));
    if (shouldRemove) {
      deleteDocument(path + "/" + queryDocumentSnapshot.getId());
    }
    return result;
  } catch (ExecutionException | InterruptedException | InvalidProtocolBufferException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #16
Source File: Guestbook.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Query Firstore for Guestbook greetings */
public List<Greeting> getGreetings() {
  // Initialize a List for Greetings.
  ImmutableList.Builder<Greeting> greetings = new ImmutableList.Builder<Greeting>();
  // Construct query.
  ApiFuture<QuerySnapshot> query =
      bookRef.collection("Greetings").orderBy("date", Direction.DESCENDING).get();

  try {
    // Get query documents.
    QuerySnapshot querySnapshot = query.get();
    for (QueryDocumentSnapshot greeting : querySnapshot.getDocuments()) {
      greetings.add(greeting.toObject(Greeting.class));
    }
  } catch (Exception e) {
    System.out.println(e.getMessage());
  }

  return greetings.build();
}
 
Example #17
Source File: ProtoQuerySnapshot.java    From startup-os with Apache License 2.0 6 votes vote down vote up
public ProtoQuerySnapshot(QuerySnapshot querySnapshot, Message.Builder builder)
    throws InvalidProtocolBufferException {
  // TODO: Avoid parsing the same objects twice in getDocuments() and getDocumentChanges().
  ImmutableList.Builder<T> protos = ImmutableList.builder();
  for (DocumentSnapshot docSnapshot : querySnapshot.getDocuments()) {
    protos.add((T) FirestoreProtoClient.parseProto(docSnapshot, builder));
  }
  this.protos = protos.build();
  ImmutableList.Builder<ProtoChange<T>> protoChanges = ImmutableList.builder();
  for (DocumentChange docChange : querySnapshot.getDocumentChanges()) {
    T proto = (T) FirestoreProtoClient.parseProto(docChange.getDocument(), builder);
    protoChanges.add(
        new ProtoChange<T>(
            proto,
            docChange.getNewIndex(),
            docChange.getOldIndex(),
            convertChangeType(docChange.getType())));
  }
  this.protoChanges = protoChanges.build();
}
 
Example #18
Source File: ListenDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Listen to a query, returning the names of all cities in the first snapshot.
 */
List<String> listenForMultiple() throws Exception {
  final SettableApiFuture<List<String>> future = SettableApiFuture.create();

  // [START listen_to_multiple]
  db.collection("cities")
      .whereEqualTo("state", "CA")
      .addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot snapshots,
                            @Nullable FirestoreException e) {
          if (e != null) {
            System.err.println("Listen failed:" + e);
            return;
          }

          List<String> cities = new ArrayList<>();
          for (DocumentSnapshot doc : snapshots) {
            if (doc.get("name") != null) {
              cities.add(doc.getString("name"));
            }
          }
          System.out.println("Current cites in CA: " + cities);
          // [START_EXCLUDE silent]
          if (!future.isDone()) {
            future.set(cities);
          }
          // [END_EXCLUDE]
        }
      });
  // [END listen_to_multiple]

  return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
 
Example #19
Source File: RetrieveDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static void deleteAllDocuments() throws Exception {
  ApiFuture<QuerySnapshot> future = db.collection("cities").get();
  QuerySnapshot querySnapshot = future.get();
  for (DocumentSnapshot doc : querySnapshot.getDocuments()) {
    // block on delete operation
    db.collection("cities").document(doc.getId()).delete().get();
  }
}
 
Example #20
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private List<String> getResults(Query query) throws Exception {
  // asynchronously retrieve query results
  ApiFuture<QuerySnapshot> future = query.get();
  // block on response
  QuerySnapshot querySnapshot = future.get();
  List<String> docIds = new ArrayList<>();
  for (DocumentSnapshot document : querySnapshot.getDocuments()) {
    docIds.add(document.getId());
  }
  return docIds;
}
 
Example #21
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleCursorConditions() throws Exception {
  // populate us_cities collection
  Map<String, String> city1 = new ImmutableMap.Builder<String, String>()
      .put("name", "Springfield").put("state", "Massachusetts").build();
  Map<String, String> city2 = new ImmutableMap.Builder<String, String>()
      .put("name", "Springfield").put("state", "Missouri").build();
  Map<String, String> city3 = new ImmutableMap.Builder<String, String>()
      .put("name", "Springfield").put("state", "Wisconsin").build();

  db.collection("us_cities").document("Massachusetts").set(city1).get();
  db.collection("us_cities").document("Missouri").set(city2).get();
  db.collection("us_cities").document("Wisconsin").set(city3).get();

  Query query1 = db.collection("us_cities")
      .orderBy("name")
      .orderBy("state")
      .startAt("Springfield");

  // all documents are retrieved
  QuerySnapshot querySnapshot = query1.get().get();
  List<QueryDocumentSnapshot> docs = querySnapshot.getDocuments();
  assertEquals(3, docs.size());


  // Will return "Springfield, Missouri" and "Springfield, Wisconsin"
  Query query2 = db.collection("us_cities")
      .orderBy("name")
      .orderBy("state")
      .startAt("Springfield", "Missouri");

  // only Missouri and Wisconsin are retrieved
  List<String> expectedResults = Arrays.asList("Missouri", "Wisconsin");
  List<String> result = getResults(query2);
  assertTrue(Objects.equals(result, expectedResults));
}
 
Example #22
Source File: QuickstartIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private void deleteAllDocuments() throws Exception {
  ApiFuture<QuerySnapshot> future = db.collection("users").get();
  QuerySnapshot querySnapshot = future.get();
  for (DocumentSnapshot doc : querySnapshot.getDocuments()) {
    // block on delete operation
    db.document("users/" + doc.getId()).delete().get();
  }
}
 
Example #23
Source File: BaseIntegrationTest.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
protected  static void deleteAllDocuments(Firestore db) throws Exception {
  ApiFuture<QuerySnapshot> future = db.collection("cities").get();
  QuerySnapshot querySnapshot = future.get();
  for (DocumentSnapshot doc : querySnapshot.getDocuments()) {
    // block on delete operation
    db.collection("cities").document(doc.getId()).delete().get();
  }
}
 
Example #24
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 5 votes vote down vote up
public List<Message> getProtoDocuments(String path, Message.Builder builder) {
  ImmutableList.Builder<Message> result = ImmutableList.builder();
  try {
    Message proto = builder.build();
    QuerySnapshot querySnapshot = getDocumentsAsync(path).get();
    for (QueryDocumentSnapshot document : querySnapshot.getDocuments()) {
      result.add(parseProto(document, builder));
    }
    return result.build();
  } catch (ExecutionException | InterruptedException | InvalidProtocolBufferException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #25
Source File: RetrieveDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Return all documents in the cities collection.
 *
 * @return list of documents
 */
public List<QueryDocumentSnapshot> getAllDocuments() throws Exception {
  // [START fs_get_all_docs]
  //asynchronously retrieve all documents
  ApiFuture<QuerySnapshot> future = db.collection("cities").get();
  // future.get() blocks on response
  List<QueryDocumentSnapshot> documents = future.get().getDocuments();
  for (QueryDocumentSnapshot document : documents) {
    System.out.println(document.getId() + " => " + document.toObject(City.class));
  }
  // [END fs_get_all_docs]
  return documents;
}
 
Example #26
Source File: RetrieveDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Return multiple documents from a collection based on a query.
 *
 * @return list of documents of capital cities.
 */
public List<QueryDocumentSnapshot> getQueryResults() throws Exception {
  // [START fs_get_multiple_docs]
  //asynchronously retrieve multiple documents
  ApiFuture<QuerySnapshot> future =
      db.collection("cities").whereEqualTo("capital", true).get();
  // future.get() blocks on response
  List<QueryDocumentSnapshot> documents = future.get().getDocuments();
  for (DocumentSnapshot document : documents) {
    System.out.println(document.getId() + " => " + document.toObject(City.class));
  }
  // [END fs_get_multiple_docs]
  return documents;
}
 
Example #27
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 4 votes vote down vote up
public ApiFuture<QuerySnapshot> getDocumentsAsync(String path) {
  return getCollectionReference(path).get();
}
 
Example #28
Source File: ListenDataSnippets.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Listen to a query, returning the list of DocumentChange events in the first snapshot.
 */
List<DocumentChange> listenForChanges() throws Exception {
  SettableApiFuture<List<DocumentChange>> future = SettableApiFuture.create();

  // [START listen_for_changes]
  db.collection("cities")
      .whereEqualTo("state", "CA")
      .addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(@Nullable QuerySnapshot snapshots,
                            @Nullable FirestoreException e) {
          if (e != null) {
            System.err.println("Listen failed: " + e);
            return;
          }

          for (DocumentChange dc : snapshots.getDocumentChanges()) {
            switch (dc.getType()) {
              case ADDED:
                System.out.println("New city: " + dc.getDocument().getData());
                break;
              case MODIFIED:
                System.out.println("Modified city: " + dc.getDocument().getData());
                break;
              case REMOVED:
                System.out.println("Removed city: " + dc.getDocument().getData());
                break;
              default:
                break;
            }
          }
          // [START_EXCLUDE silent]
          if (!future.isDone()) {
            future.set(snapshots.getDocumentChanges());
          }
          // [END_EXCLUDE]
        }
      });
  // [END listen_for_changes]

  return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
 
Example #29
Source File: MyDataStore.java    From smart-home-java with Apache License 2.0 4 votes vote down vote up
public List<QueryDocumentSnapshot> getDevices(String userId)
    throws ExecutionException, InterruptedException {
  ApiFuture<QuerySnapshot> deviceQuery =
      database.collection("users").document(userId).collection("devices").get();
  return deviceQuery.get().getDocuments();
}