com.google.cloud.firestore.Query Java Examples

The following examples show how to use com.google.cloud.firestore.Query. 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: 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 #2
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 #3
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 #4
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 #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: 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 #7
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 #8
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 #9
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateAQuery() throws Exception {
  Query q = queryDataSnippets.createAQuery();
  Set<String> result = getResultsAsSet(q);
  Set<String> expectedResults = new HashSet<>(Arrays.asList("DC", "TOK", "BJ"));
  assertTrue(Objects.equals(result, expectedResults));
}
 
Example #10
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleQueryReturnsExpectedResults() throws Exception {
  List<Set<String>> expectedResults = new ArrayList<>();

  expectedResults.add(new HashSet<>(Arrays.asList("SF", "LA")));
  expectedResults.add(new HashSet<>(Arrays.asList("SF", "DC")));
  expectedResults.add(new HashSet<>(Arrays.asList("SF", "DC", "TOK")));

  List<Query> queries = queryDataSnippets.createSimpleQueries();
  for (int i = 0; i < queries.size(); i++) {
    Set<String> results = getResultsAsSet(queries.get(i));
    assertTrue(Objects.equals(results, expectedResults.get(i)));
  }
}
 
Example #11
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testArrayQueryReturnsExpectedResults() throws Exception {
  Set<String> expected = new HashSet<>(Arrays.asList("SF", "LA"));

  Query query = queryDataSnippets.createArrayQuery();
  Set<String> results = getResultsAsSet(query);

  assertTrue(Objects.equals(results, expected));
}
 
Example #12
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testChainedQuery() throws Exception {
  Query q = queryDataSnippets.createChainedQuery();
  Set<String> result = getResultsAsSet(q);
  Set<String> expectedResults = new HashSet<>();
  assertTrue(Objects.equals(result, expectedResults));
}
 
Example #13
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testRangeQuery() throws Exception {
  Query q = queryDataSnippets.createRangeQuery();
  Set<String> result = getResultsAsSet(q);
  Set<String> expectedResults = new HashSet<>(Arrays.asList("SF", "LA"));
  assertTrue(Objects.equals(result, expectedResults));
}
 
Example #14
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderByNameWithLimitQuery() throws Exception {
  Query q = queryDataSnippets.createOrderByNameWithLimitQuery();
  List<String> result = getResults(q);
  List<String> expectedResults = Arrays.asList("BJ", "LA", "SF");
  assertEquals(result, expectedResults);
}
 
Example #15
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderByNameWithLimitToLastQuery() throws Exception {
  Query q = queryDataSnippets.createOrderByNameWithLimitToLastQuery();
  List<String> result = getResults(q);
  List<String> expectedResults = Arrays.asList("SF", "TOK", "DC");
  assertEquals(result, expectedResults);
}
 
Example #16
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderByNameDescWithLimitQuery() throws Exception {
  Query q = queryDataSnippets.createOrderByNameDescWithLimitQuery();
  List<String> result = getResults(q);
  List<String> expectedResults = Arrays.asList("DC", "TOK", "SF");
  assertTrue(Objects.equals(result, expectedResults));
}
 
Example #17
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testWhereWithOrderByAndLimitQuery() throws Exception {
  Query q = queryDataSnippets.createWhereWithOrderByAndLimitQuery();
  List<String> result = getResults(q);
  List<String> expectedResults = Arrays.asList("LA", "TOK");
  assertEquals(result, expectedResults);
}
 
Example #18
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testRangeWithOrderByQuery() throws Exception {
  Query q = queryDataSnippets.createRangeWithOrderByQuery();
  List<String> result = getResults(q);
  List<String> expectedResults = Arrays.asList("LA", "TOK", "BJ");
  assertEquals(result, expectedResults);
}
 
Example #19
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartAtFieldQueryCursor() throws Exception {
  Query q = queryDataSnippets.createStartAtFieldQueryCursor();
  List<String> expectedResults = Arrays.asList("TOK", "BJ");
  List<String> result = getResults(q);
  assertTrue(Objects.equals(result, expectedResults));
}
 
Example #20
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndAtFieldQueryCursor() throws Exception {
  Query q = queryDataSnippets.createEndAtFieldQueryCursor();
  List<String> expectedResults = Arrays.asList("DC", "SF", "LA");
  List<String> result = getResults(q);
  assertEquals(result, expectedResults);
}
 
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: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateStartAtSnapshotQueryCursor() throws Exception {
  Query q = queryDataSnippets.createStartAtSnapshotQueryCursor();
  List<String> results = getResults(q);
  List<String> expectedResults = Arrays.asList("SF", "LA", "TOK", "BJ");
  assertEquals(expectedResults, results);
}
 
Example #23
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testPaginateCursor() throws Exception {
  // Snippet executes it's own query. Failures result in thrown Exceptions
  List<Query> pages = queryDataSnippets.paginateCursor();
  List<String> firstPage = getResults(pages.get(0));
  List<String> secondPage = getResults(pages.get(1));
  assertEquals(Arrays.asList("DC", "SF", "LA", "TOK", "BJ"), firstPage);
  assertEquals(new ArrayList<String>(), secondPage);
}
 
Example #24
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryFilterArrayContainsAny() throws Exception {
  Query query = queryDataSnippets.arrayContainsAnyQueries();
  Set<String> expected = newHashSet("SF", "LA", "DC");
  Set<String> actual = getResultsAsSet(query);
  assertEquals(expected, actual);
}
 
Example #25
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryFilterInQueryWithoutArray() throws Exception {
  Query query = queryDataSnippets.inQueryWithoutArray();
  Set<String> expected = newHashSet("SF", "LA", "DC", "TOK");
  Set<String> actual = getResultsAsSet(query);
  assertEquals(expected, actual);
}
 
Example #26
Source File: QueryDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryFilterInQueryWithArray() throws Exception {
  Query query = queryDataSnippets.inQueryWithArray();
  Set<String> expected = newHashSet("DC");
  Set<String> actual = getResultsAsSet(query);
  assertEquals(expected, actual);
}
 
Example #27
Source File: FirestoreQueryFactory.java    From elepy with Apache License 2.0 5 votes vote down vote up
public static Query getQuery(Query query, Filter filter, Schema schema) {

        final var propertyName = filter.getPropertyName();

        final var value = filter.getFilterValue();
        final var property = schema.getProperty(propertyName);
        switch (filter.getFilterType()) {
            case EQUALS:
                return query.whereEqualTo(propertyName, value);
            case GREATER_THAN:
                return query.whereGreaterThan(propertyName, value);
            case GREATER_THAN_OR_EQUALS:
                return query.whereGreaterThanOrEqualTo(propertyName, value);
            case LESSER_THAN:
                return query.whereLessThan(propertyName, value);
            case LESSER_THAN_OR_EQUALS:
                return query.whereLessThanOrEqualTo(propertyName, value);
            case CONTAINS:
                if (property.getType().equals(FieldType.ARRAY)) {
                    return query.whereArrayContains(propertyName, value);
                } else {
                    throw new ElepyException("Firestore 'CONTAINS' only works on arrays");
                }
            case IS_NULL:
                return query.whereEqualTo(propertyName, null);
            default:
                throw new ElepyException("Firestore does not support the filter: " + filter.getFilterType().getName());
        }

    }
 
Example #28
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 #29
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;
}
 
Example #30
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;
}