Skip to content

Commit 4099e5b

Browse files
authored
feat: Add additional Firestore query snippets (#1790)
* firestore sample for multiple inequality * fix typo * format code * change samples to be in own file * Create maven.yml * Delete .github/workflows/maven.yml * change query to lowercase to pass test case * fix checkstyle lint error * update copyright dates
1 parent 20b5148 commit 4099e5b

File tree

2 files changed

+237
-0
lines changed

2 files changed

+237
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
/*
2+
* Copyright 2024 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.firestore.snippets;
18+
19+
import com.example.firestore.snippets.model.City;
20+
import com.google.api.core.ApiFuture;
21+
import com.google.api.core.ApiFutures;
22+
import com.google.cloud.firestore.CollectionReference;
23+
import com.google.cloud.firestore.DocumentSnapshot;
24+
import com.google.cloud.firestore.Firestore;
25+
import com.google.cloud.firestore.Query;
26+
import com.google.cloud.firestore.Query.Direction;
27+
import com.google.cloud.firestore.QueryDocumentSnapshot;
28+
import com.google.cloud.firestore.QuerySnapshot;
29+
import com.google.cloud.firestore.WriteResult;
30+
import java.util.ArrayList;
31+
import java.util.Arrays;
32+
import java.util.HashMap;
33+
import java.util.List;
34+
import java.util.Map;
35+
import java.util.concurrent.ExecutionException;
36+
import java.util.concurrent.TimeUnit;
37+
import java.util.concurrent.TimeoutException;
38+
39+
/**
40+
* Snippets to support firestore querying data documentation.
41+
*/
42+
class MultipleRangeInequalityFiltersSnippets {
43+
44+
private final Firestore db;
45+
46+
MultipleRangeInequalityFiltersSnippets(Firestore db) {
47+
this.db = db;
48+
}
49+
50+
/**
51+
* Creates cities collection and add sample documents to test queries.
52+
*/
53+
void prepareExamples() throws Exception {
54+
// Data for each city
55+
Map<String, Object> sfData = new HashMap<>();
56+
sfData.put("name", "San Francisco");
57+
sfData.put("state", "CA");
58+
sfData.put("country", "USA");
59+
sfData.put("capital", false);
60+
sfData.put("population", 860000L);
61+
sfData.put("density", 18000L);
62+
sfData.put("regions", Arrays.asList("west_coast", "norcal"));
63+
64+
Map<String, Object> laData = new HashMap<>();
65+
laData.put("name", "Los Angeles");
66+
laData.put("state", "CA");
67+
laData.put("country", "USA");
68+
laData.put("capital", false);
69+
laData.put("population", 3900000L);
70+
laData.put("density", 8300L);
71+
laData.put("regions", Arrays.asList("west_coast", "socal"));
72+
73+
Map<String, Object> dcData = new HashMap<>();
74+
dcData.put("name", "Washington D.C.");
75+
dcData.put("state", null);
76+
dcData.put("country", "USA");
77+
dcData.put("capital", true);
78+
dcData.put("population", 680000L);
79+
dcData.put("density", 11300L);
80+
dcData.put("regions", Arrays.asList("east_coast"));
81+
82+
Map<String, Object> tokData = new HashMap<>();
83+
tokData.put("name", "Tokyo");
84+
tokData.put("state", null);
85+
tokData.put("country", "Japan");
86+
tokData.put("capital", true);
87+
tokData.put("population", 9000000L);
88+
tokData.put("density", 16000L);
89+
tokData.put("regions", Arrays.asList("kanto", "honshu"));
90+
91+
Map<String, Object> bjData = new HashMap<>();
92+
bjData.put("name", "Beijing");
93+
bjData.put("state", null);
94+
bjData.put("country", "China");
95+
bjData.put("capital", true);
96+
bjData.put("population", 21500000L);
97+
bjData.put("density", 3500L);
98+
bjData.put("regions", Arrays.asList("jingjinji", "hebei"));
99+
100+
CollectionReference citiesCollection = db.collection("cities");
101+
102+
// Add each city document
103+
addCityDocument(citiesCollection, "SF", sfData);
104+
addCityDocument(citiesCollection, "LA", laData);
105+
addCityDocument(citiesCollection, "DC", dcData);
106+
addCityDocument(citiesCollection, "TOK", tokData);
107+
addCityDocument(citiesCollection, "BJ", bjData);
108+
109+
System.out.println("Data added successfully!");
110+
}
111+
112+
private static void addCityDocument(CollectionReference citiesRef, String documentId,
113+
Map<String, Object> data) {
114+
ApiFuture<WriteResult> future = citiesRef.document(documentId).set(data);
115+
try {
116+
WriteResult result = future.get();
117+
System.out.println("Update time : " + result.getUpdateTime());
118+
} catch (Exception e) {
119+
System.err.println("Error adding document: " + e.getMessage());
120+
}
121+
}
122+
123+
/* Example of Query with range and inequality filters. */
124+
Query compoundMultiInequalities() {
125+
// [START firestore_query_filter_compound_multi_ineq]
126+
Query query = db.collection("cities")
127+
.whereGreaterThan("population", 1000000)
128+
.whereLessThan("density", 10000);
129+
// [END firestore_query_filter_compound_multi_ineq]
130+
return query;
131+
}
132+
133+
/* Example of filtering indexes considering performance reasons. */
134+
void indexingConsiderations() {
135+
// [START firestore_query_indexing_considerations]
136+
db.collection("employees")
137+
.whereGreaterThan("salary", 100000)
138+
.whereGreaterThan("experience", 0)
139+
.orderBy("salary")
140+
.orderBy("experience");
141+
// [END firestore_query_indexing_considerations]
142+
}
143+
144+
/**
145+
* Closes the gRPC channels associated with this instance and frees up their resources.
146+
*/
147+
void close() throws Exception {
148+
db.close();
149+
}
150+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
* Copyright 2024 Google Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.firestore.snippets;
18+
19+
import static com.google.common.collect.Sets.newHashSet;
20+
import static org.junit.Assert.assertEquals;
21+
import static org.junit.Assert.assertTrue;
22+
23+
import com.example.firestore.BaseIntegrationTest;
24+
import com.google.api.core.ApiFuture;
25+
import com.google.cloud.firestore.DocumentSnapshot;
26+
import com.google.cloud.firestore.Query;
27+
import com.google.cloud.firestore.QueryDocumentSnapshot;
28+
import com.google.cloud.firestore.QuerySnapshot;
29+
import com.google.common.collect.ImmutableMap;
30+
import java.util.ArrayList;
31+
import java.util.Arrays;
32+
import java.util.HashSet;
33+
import java.util.List;
34+
import java.util.Map;
35+
import java.util.Objects;
36+
import java.util.Set;
37+
import org.junit.AfterClass;
38+
import org.junit.BeforeClass;
39+
import org.junit.Test;
40+
import org.junit.runner.RunWith;
41+
import org.junit.runners.JUnit4;
42+
43+
@RunWith(JUnit4.class)
44+
@SuppressWarnings("checkstyle:abbreviationaswordinname")
45+
public class MultipleRangeInequalityFiltersSnippetsIT extends BaseIntegrationTest {
46+
47+
private static MultipleRangeInequalityFiltersSnippets multipleRangeInequalityFiltersSnippets;
48+
49+
@BeforeClass
50+
public static void setUpBeforeClass() throws Exception {
51+
multipleRangeInequalityFiltersSnippets = new MultipleRangeInequalityFiltersSnippets(db);
52+
multipleRangeInequalityFiltersSnippets.prepareExamples();
53+
}
54+
55+
@Test
56+
public void testRangeMultipleInequalityFilter() throws Exception {
57+
Query query = multipleRangeInequalityFiltersSnippets.compoundMultiInequalities();
58+
59+
Set<String> expected = newHashSet("BJ", "LA");
60+
Set<String> actual = getResultsAsSet(query);
61+
assertEquals(expected, actual);
62+
}
63+
64+
private Set<String> getResultsAsSet(Query query) throws Exception {
65+
List<String> docIds = getResults(query);
66+
return new HashSet<>(docIds);
67+
}
68+
69+
private List<String> getResults(Query query) throws Exception {
70+
// asynchronously retrieve query results
71+
ApiFuture<QuerySnapshot> future = query.get();
72+
// block on response
73+
QuerySnapshot querySnapshot = future.get();
74+
75+
List<String> docIds = new ArrayList<>();
76+
for (DocumentSnapshot document : querySnapshot.getDocuments()) {
77+
docIds.add(document.getId());
78+
}
79+
return docIds;
80+
}
81+
82+
@AfterClass
83+
public static void tearDown() throws Exception {
84+
deleteAllDocuments(db);
85+
multipleRangeInequalityFiltersSnippets.close();
86+
}
87+
}

0 commit comments

Comments
 (0)