-
Notifications
You must be signed in to change notification settings - Fork 66
/
QueryDataSnippets.java
652 lines (601 loc) · 22.1 KB
/
QueryDataSnippets.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.firestore.snippets;
import com.example.firestore.snippets.model.City;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.cloud.firestore.CollectionReference;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.Query;
import com.google.cloud.firestore.Query.Direction;
import com.google.cloud.firestore.QueryDocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import com.google.cloud.firestore.WriteResult;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/** Snippets to support firestore querying data documentation. */
class QueryDataSnippets {
private final Firestore db;
QueryDataSnippets(Firestore db) {
this.db = db;
}
/**
* Creates cities collection and add sample documents to test queries.
*
* @return collection reference
*/
void prepareExamples() throws Exception {
// [START fs_query_create_examples]
// [START firestore_query_filter_dataset]
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 documents successfully added
ApiFutures.allAsList(futures).get();
// [END firestore_query_filter_dataset]
// [END fs_query_create_examples]
}
/**
* Creates a sample query.
*
* @return query
*/
Query createQuery() throws Exception {
// [START fs_create_query]
// [START firestore_query_filter_eq_boolean]
// 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 firestore_query_filter_eq_boolean]
// [END fs_create_query]
return query;
}
/**
* Creates a sample query.
*
* @return query
*/
Query createQueryAlternate() throws Exception {
// [START fs_create_query_country]
// [START firestore_query_filter_eq_string]
// 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 firestore_query_filter_eq_string]
// [END fs_create_query_country]
return query;
}
/**
* 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]
// [START firestore_query_filter_single_examples]
Query stateQuery = cities.whereEqualTo("state", "CA");
Query populationQuery = cities.whereLessThan("population", 1000000L);
Query nameQuery = cities.whereGreaterThanOrEqualTo("name", "San Francisco");
// [END firestore_query_filter_single_examples]
// [END fs_simple_queries]
querys.add(stateQuery);
querys.add(populationQuery);
querys.add(nameQuery);
return querys;
}
/**
* Creates a query based on array containment.
*
* @return query
*/
Query createArrayQuery() {
// [START fs_array_contains_filter]
// [START firestore_query_filter_array_contains]
CollectionReference citiesRef = db.collection("cities");
Query westCoastQuery = citiesRef.whereArrayContains("regions", "west_coast");
// [END firestore_query_filter_array_contains]
// [END fs_array_contains_filter]
return westCoastQuery;
}
/**
* 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]
// [START firestore_query_filter_compound_multi_eq]
Query chainedQuery1 = cities.whereEqualTo("state", "CO").whereEqualTo("name", "Denver");
// [END firestore_query_filter_compound_multi_eq]
// [END fs_chained_query]
return chainedQuery1;
}
/**
* 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]
// [START firestore_query_filter_compound_multi_eq_lt]
Query chainedQuery2 = cities.whereEqualTo("state", "CA").whereLessThan("population", 1000000L);
// [END firestore_query_filter_compound_multi_eq_lt]
// [END fs_composite_index_chained_query]
return chainedQuery2;
}
/**
* 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]
// [START firestore_query_filter_range_valid]
Query validQuery1 =
cities.whereGreaterThanOrEqualTo("state", "CA").whereLessThanOrEqualTo("state", "IN");
Query validQuery2 = cities.whereEqualTo("state", "CA").whereGreaterThan("population", 1000000);
// [END firestore_query_filter_range_valid]
// [END fs_range_query]
return validQuery1;
}
/**
* 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]
// [START firestore_query_filter_range_invalid]
Query invalidRangeQuery =
cities.whereGreaterThanOrEqualTo("state", "CA").whereGreaterThan("population", 100000);
// [END firestore_query_filter_range_invalid]
// [END fs_invalid_range_query]
return invalidRangeQuery;
}
/**
* 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]
// [START firestore_query_order_limit]
Query query = cities.orderBy("name").limit(3);
// [END firestore_query_order_limit]
// [END fs_order_by_name_limit_query]
return query;
}
/**
* 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]
// [START firestore_query_order_limit]
Query query = cities.orderBy("name").limitToLast(3);
// [END firestore_query_order_limit]
// [END fs_order_by_name_limit_query]
return query;
}
/**
* 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]
// [START firestore_query_order_multi]
Query query = cities.orderBy("state").orderBy("population", Direction.DESCENDING);
// [END firestore_query_order_multi]
// [END fs_order_by_country_population]
return query;
}
/**
* 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]
// [START firestore_query_order_desc_limit]
Query query = cities.orderBy("name", Direction.DESCENDING).limit(3);
// [END firestore_query_order_desc_limit]
// [END fs_order_by_name_desc_limit_query]
return query;
}
/**
* 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]
// [START firestore_query_order_limit_field_valid]
Query query = cities.whereGreaterThan("population", 2500000L).orderBy("population").limit(2);
// [END firestore_query_order_limit_field_valid]
// [END fs_where_order_by_limit_query]
return query;
}
/**
* 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;
}
/**
* 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]
// [START firestore_query_order_field_invalid]
Query query = cities.whereGreaterThan("population", 2500000L).orderBy("country");
// [END firestore_query_order_field_invalid]
// [END fs_invalid_range_order_by_query]
return query;
}
/**
* 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]
// [START firestore_query_cursor_start_at_field_value_single]
Query query = cities.orderBy("population").startAt(4921000L);
// [END firestore_query_cursor_start_at_field_value_single]
// [END fs_start_at_field_query_cursor]
return query;
}
/**
* 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]
// [START firestore_query_cursor_end_at_field_value_single]
Query query = cities.orderBy("population").endAt(4921000L);
// [END firestore_query_cursor_end_at_field_value_single]
// [END fs_end_at_field_query_cursor]
return query;
}
/* Create queries with multiple cursor conditions. */
void createMultipleCursorConditionsQuery() {
// [START fs_multiple_cursor_conditions]
// [START firestore_query_cursor_start_at_field_value_multi]
// Will return all Springfields
Query query1 = db.collection("cities").orderBy("name").orderBy("state").startAt("Springfield");
// Will return "Springfield, Missouri" and "Springfield, Wisconsin"
Query query2 =
db.collection("cities").orderBy("name").orderBy("state").startAt("Springfield", "Missouri");
// [END firestore_query_cursor_start_at_field_value_multi]
// [END fs_multiple_cursor_conditions]
}
/**
* Create a query using a snapshot as a start point.
*
* @return query
*/
Query createStartAtSnapshotQueryCursor()
throws InterruptedException, ExecutionException, TimeoutException {
// [START fs_document_snapshot_cursor]
// [START firestore_query_cursor_start_at_document]
// Fetch the snapshot with an API call, waiting for a maximum of 30 seconds for a result.
ApiFuture<DocumentSnapshot> future = db.collection("cities").document("SF").get();
DocumentSnapshot snapshot = future.get(30, TimeUnit.SECONDS);
// Construct the query
Query query = db.collection("cities").orderBy("population").startAt(snapshot);
// [END firestore_query_cursor_start_at_document]
// [END fs_document_snapshot_cursor]
return query;
}
/** Example of a paginated query. */
List<Query> paginateCursor() throws InterruptedException, ExecutionException, TimeoutException {
// [START fs_paginate_cursor]
// [START firestore_query_cursor_pagination]
// 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 firestore_query_cursor_pagination]
// [END fs_paginate_cursor]
return Arrays.asList(firstPage, secondPage);
}
void collectionGroupQuery() throws ExecutionException, InterruptedException {
// CHECKSTYLE OFF: Indentation
// CHECKSTYLE OFF: RightCurlyAlone
// [START fs_collection_group_query_data_setup]
// [START firestore_query_collection_group_dataset]
CollectionReference cities = db.collection("cities");
final List<ApiFuture<WriteResult>> futures =
Arrays.asList(
cities
.document("SF")
.collection("landmarks")
.document()
.set(
new HashMap<String, String>() {
{
put("name", "Golden Gate Bridge");
put("type", "bridge");
}
}),
cities
.document("SF")
.collection("landmarks")
.document()
.set(
new HashMap<String, String>() {
{
put("name", "Legion of Honor");
put("type", "museum");
}
}),
cities
.document("LA")
.collection("landmarks")
.document()
.set(
new HashMap<String, String>() {
{
put("name", "Griffith Park");
put("type", "park");
}
}),
cities
.document("LA")
.collection("landmarks")
.document()
.set(
new HashMap<String, String>() {
{
put("name", "The Getty");
put("type", "museum");
}
}),
cities
.document("DC")
.collection("landmarks")
.document()
.set(
new HashMap<String, String>() {
{
put("name", "Lincoln Memorial");
put("type", "memorial");
}
}),
cities
.document("DC")
.collection("landmarks")
.document()
.set(
new HashMap<String, String>() {
{
put("name", "National Air and Space Museum");
put("type", "museum");
}
}),
cities
.document("TOK")
.collection("landmarks")
.document()
.set(
new HashMap<String, String>() {
{
put("name", "Ueno Park");
put("type", "park");
}
}),
cities
.document("TOK")
.collection("landmarks")
.document()
.set(
new HashMap<String, String>() {
{
put("name", "National Museum of Nature and Science");
put("type", "museum");
}
}),
cities
.document("BJ")
.collection("landmarks")
.document()
.set(
new HashMap<String, String>() {
{
put("name", "Jingshan Park");
put("type", "park");
}
}),
cities
.document("BJ")
.collection("landmarks")
.document()
.set(
new HashMap<String, String>() {
{
put("name", "Beijing Ancient Observatory");
put("type", "museum");
}
}));
final List<WriteResult> landmarks = ApiFutures.allAsList(futures).get();
// [END firestore_query_collection_group_dataset]
// [END fs_collection_group_query_data_setup]
// [START fs_collection_group_query]
// [START firestore_query_collection_group_filter_eq]
final Query museums = db.collectionGroup("landmarks").whereEqualTo("type", "museum");
final ApiFuture<QuerySnapshot> querySnapshot = museums.get();
for (DocumentSnapshot document : querySnapshot.get().getDocuments()) {
System.out.println(document.getId());
}
// [END firestore_query_collection_group_filter_eq]
// [END fs_collection_group_query]
// CHECKSTYLE ON: RightCurlyAlone
// CHECKSTYLE ON: Indentation
}
public Query arrayContainsAnyQueries() {
// [START fs_query_filter_array_contains_any]
// [START firestore_query_filter_array_contains_any]
CollectionReference citiesRef = db.collection("cities");
Query query =
citiesRef.whereArrayContainsAny("regions", Arrays.asList("west_coast", "east_coast"));
// [END firestore_query_filter_array_contains_any]
// [END fs_query_filter_array_contains_any]
return query;
}
public Query inQueryWithoutArray() {
// [START fs_query_filter_in]
// [START firestore_query_filter_in]
CollectionReference citiesRef = db.collection("cities");
Query query = citiesRef.whereIn("country", Arrays.asList("USA", "Japan"));
// [END firestore_query_filter_in]
// [END fs_query_filter_in]
return query;
}
public Query inQueryWithArray() {
// [START fs_query_filter_in_with_array]
// [START firestore_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 firestore_query_filter_in_with_array]
// [END fs_query_filter_in_with_array]
return query;
}
Query notEqualsQuery() {
// [START fs_query_not_equals]
// [START firestore_query_filter_not_eq]
CollectionReference citiesRef = db.collection("cities");
Query query = citiesRef.whereNotEqualTo("capital", false);
// [END firestore_query_filter_not_eq]
// [END fs_query_not_equals]
return query;
}
Query filterNotIn() {
// [START fs_filter_not_in]
// [START firestore_query_filter_not_in]
CollectionReference citiesRef = db.collection("cities");
Query query = citiesRef.whereNotIn("country", Arrays.asList("USA", "Japan"));
// [END firestore_query_filter_not_in]
// [END fs_filter_not_in]
return query;
}
/** Closes the gRPC channels associated with this instance and frees up their resources. */
void close() throws Exception {
db.close();
}
}