-
Notifications
You must be signed in to change notification settings - Fork 401
/
DocSnippets.kt
1230 lines (1067 loc) · 39.9 KB
/
DocSnippets.kt
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
863
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@file:Suppress("UNUSED_VARIABLE", "UNUSED_ANONYMOUS_PARAMETER")
package com.google.example.firestore.kotlin
import android.util.Log
import com.google.firebase.Timestamp
import com.google.firebase.firestore.AggregateField
import com.google.firebase.firestore.AggregateSource
import com.google.firebase.firestore.DocumentChange
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.firestore.MetadataChanges
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.ServerTimestamp
import com.google.firebase.firestore.SetOptions
import com.google.firebase.firestore.Source
import com.google.firebase.firestore.firestore
import com.google.firebase.firestore.firestoreSettings
import com.google.firebase.firestore.memoryCacheSettings
import com.google.firebase.firestore.persistentCacheSettings
import com.google.firebase.firestore.toObject
import com.google.firebase.Firebase
import java.util.ArrayList
import java.util.Date
import java.util.HashMap
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
/**
* Kotlin version of doc snippets.
*
*/
abstract class DocSnippets(val db: FirebaseFirestore) {
companion object {
private val TAG = "DocSnippets"
private val EXECUTOR = ThreadPoolExecutor(
2,
4,
60,
TimeUnit.SECONDS,
LinkedBlockingQueue(),
)
}
internal fun runAll() {
Log.d(TAG, "================= BEGIN RUN ALL ===============")
// Write example data
exampleData()
exampleDataCollectionGroup()
// Run all other methods
addAdaLovelace()
addAlanTuring()
getAllUsers()
listenForUsers()
docReference()
collectionReference()
subcollectionReference()
setDocument()
dataTypes()
addDocument()
newDocument()
updateDocument()
updateDocumentNested()
setFieldWithMerge()
deleteDocument()
transactions()
transactionPromise()
getDocument()
getDocumentWithOptions()
listenToDocument()
listenToDocumentLocal()
getMultipleDocs()
getAllDocs()
listenToMultiple()
listenToDiffs()
listenState()
detachListener()
handleListenErrors()
simpleQueries()
compoundQueries()
orderAndLimit()
queryStartAtEndAt()
collectionGroupQuery()
// Run methods that should fail
try {
compoundQueriesInvalid()
} catch (e: Exception) {
Log.d(TAG, "compoundQueriesInvalid", e)
}
try {
orderAndLimitInvalid()
} catch (e: Exception) {
Log.d(TAG, "orderAndLimitInvalid", e)
}
}
private fun setup() {
// [START get_firestore_instance]
val db = Firebase.firestore
// [END get_firestore_instance]
// [START set_firestore_settings]
val settings = firestoreSettings {
// Use memory cache
setLocalCacheSettings(memoryCacheSettings {})
// Use persistent disk cache (default)
setLocalCacheSettings(persistentCacheSettings {})
}
db.firestoreSettings = settings
// [END set_firestore_settings]
}
private fun setupCacheSize() {
// [START fs_setup_cache]
val settings = firestoreSettings {
setLocalCacheSettings(persistentCacheSettings {
// Set size to 100 MB
setSizeBytes(1024 * 1024 * 100)
})
}
db.firestoreSettings = settings
// [END fs_setup_cache]
}
private fun addAdaLovelace() {
// [START add_ada_lovelace]
// Create a new user with a first and last name
val user = hashMapOf(
"first" to "Ada",
"last" to "Lovelace",
"born" to 1815,
)
// Add a new document with a generated ID
db.collection("users")
.add(user)
.addOnSuccessListener { documentReference ->
Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
}
.addOnFailureListener { e ->
Log.w(TAG, "Error adding document", e)
}
// [END add_ada_lovelace]
}
private fun addAlanTuring() {
// [START add_alan_turing]
// Create a new user with a first, middle, and last name
val user = hashMapOf(
"first" to "Alan",
"middle" to "Mathison",
"last" to "Turing",
"born" to 1912,
)
// Add a new document with a generated ID
db.collection("users")
.add(user)
.addOnSuccessListener { documentReference ->
Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
}
.addOnFailureListener { e ->
Log.w(TAG, "Error adding document", e)
}
// [END add_alan_turing]
}
private fun getAllUsers() {
// [START get_all_users]
db.collection("users")
.get()
.addOnSuccessListener { result ->
for (document in result) {
Log.d(TAG, "${document.id} => ${document.data}")
}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Error getting documents.", exception)
}
// [END get_all_users]
}
private fun listenForUsers() {
// [START listen_for_users]
// Listen for users born before 1900.
//
// You will get a first snapshot with the initial results and a new
// snapshot each time there is a change in the results.
db.collection("users")
.whereLessThan("born", 1900)
.addSnapshotListener { snapshots, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@addSnapshotListener
}
Log.d(TAG, "Current users born before 1900: $snapshots")
}
// [END listen_for_users]
}
private fun docReference() {
// [START doc_reference]
val alovelaceDocumentRef = db.collection("users").document("alovelace")
// [END doc_reference]
}
private fun collectionReference() {
// [START collection_reference]
val usersCollectionRef = db.collection("users")
// [END collection_reference]
}
private fun subcollectionReference() {
// [START subcollection_reference]
val messageRef = db
.collection("rooms").document("roomA")
.collection("messages").document("message1")
// [END subcollection_reference]
}
fun docReferenceAlternate() {
// [START doc_reference_alternate]
val alovelaceDocumentRef = db.document("users/alovelace")
// [END doc_reference_alternate]
}
// [START city_class]
data class City(
val name: String? = null,
val state: String? = null,
val country: String? = null,
@field:JvmField // use this annotation if your Boolean field is prefixed with 'is'
val isCapital: Boolean? = null,
val population: Long? = null,
val regions: List<String>? = null,
)
// [END city_class]
private fun setDocument() {
// [START set_document]
val city = hashMapOf(
"name" to "Los Angeles",
"state" to "CA",
"country" to "USA",
)
db.collection("cities").document("LA")
.set(city)
.addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") }
.addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) }
// [END set_document]
val data = HashMap<String, Any>()
// [START set_with_id]
db.collection("cities").document("new-city-id").set(data)
// [END set_with_id]
}
private fun dataTypes() {
// [START data_types]
val docData = hashMapOf(
"stringExample" to "Hello world!",
"booleanExample" to true,
"numberExample" to 3.14159265,
"dateExample" to Timestamp(Date()),
"listExample" to arrayListOf(1, 2, 3),
"nullExample" to null,
)
val nestedData = hashMapOf(
"a" to 5,
"b" to true,
)
docData["objectExample"] = nestedData
db.collection("data").document("one")
.set(docData)
.addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") }
.addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) }
// [END data_types]
}
fun addCustomClass() {
// [START add_custom_class]
val city = City(
"Los Angeles",
"CA",
"USA",
false,
5000000L,
listOf("west_coast", "socal"),
)
db.collection("cities").document("LA").set(city)
// [END add_custom_class]
}
private fun addDocument() {
// [START add_document]
// Add a new document with a generated id.
val data = hashMapOf(
"name" to "Tokyo",
"country" to "Japan",
)
db.collection("cities")
.add(data)
.addOnSuccessListener { documentReference ->
Log.d(TAG, "DocumentSnapshot written with ID: ${documentReference.id}")
}
.addOnFailureListener { e ->
Log.w(TAG, "Error adding document", e)
}
// [END add_document]
}
private fun newDocument() {
// [START new_document]
val data = HashMap<String, Any>()
val newCityRef = db.collection("cities").document()
// Later...
newCityRef.set(data)
// [END new_document]
}
private fun updateDocument() {
// [START update_document]
val washingtonRef = db.collection("cities").document("DC")
// Set the "isCapital" field of the city 'DC'
washingtonRef
.update("capital", true)
.addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully updated!") }
.addOnFailureListener { e -> Log.w(TAG, "Error updating document", e) }
// [END update_document]
}
fun updateDocumentArray() {
// [START update_document_array]
val washingtonRef = db.collection("cities").document("DC")
// Atomically add a new region to the "regions" array field.
washingtonRef.update("regions", FieldValue.arrayUnion("greater_virginia"))
// Atomically remove a region from the "regions" array field.
washingtonRef.update("regions", FieldValue.arrayRemove("east_coast"))
// [END update_document_array]
}
fun updateDocumentIncrement() {
// [START update_document_increment]
val washingtonRef = db.collection("cities").document("DC")
// Atomically increment the population of the city by 50.
washingtonRef.update("population", FieldValue.increment(50))
// [END update_document_increment]
}
private fun updateDocumentNested() {
// [START update_document_nested]
// Assume the document contains:
// {
// name: "Frank",
// favorites: { food: "Pizza", color: "Blue", subject: "recess" }
// age: 12
// }
//
// To update age and favorite color:
db.collection("users").document("frank")
.update(
mapOf(
"age" to 13,
"favorites.color" to "Red",
),
)
// [END update_document_nested]
}
private fun setFieldWithMerge() {
// [START set_field_with_merge]
// Update one field, creating the document if it does not already exist.
val data = hashMapOf("capital" to true)
db.collection("cities").document("BJ")
.set(data, SetOptions.merge())
// [END set_field_with_merge]
}
private fun deleteDocument() {
// [START delete_document]
db.collection("cities").document("DC")
.delete()
.addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully deleted!") }
.addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) }
// [END delete_document]
}
private fun transactions() {
// [START transactions]
val sfDocRef = db.collection("cities").document("SF")
db.runTransaction { transaction ->
val snapshot = transaction.get(sfDocRef)
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
val newPopulation = snapshot.getDouble("population")!! 1
transaction.update(sfDocRef, "population", newPopulation)
// Success
null
}.addOnSuccessListener { Log.d(TAG, "Transaction success!") }
.addOnFailureListener { e -> Log.w(TAG, "Transaction failure.", e) }
// [END transactions]
}
private fun transactionPromise() {
// [START transaction_with_result]
val sfDocRef = db.collection("cities").document("SF")
db.runTransaction { transaction ->
val snapshot = transaction.get(sfDocRef)
val newPopulation = snapshot.getDouble("population")!! 1
if (newPopulation <= 1000000) {
transaction.update(sfDocRef, "population", newPopulation)
newPopulation
} else {
throw FirebaseFirestoreException(
"Population too high",
FirebaseFirestoreException.Code.ABORTED,
)
}
}.addOnSuccessListener { result ->
Log.d(TAG, "Transaction success: $result")
}.addOnFailureListener { e ->
Log.w(TAG, "Transaction failure.", e)
}
// [END transaction_with_result]
}
fun writeBatch() {
// [START write_batch]
val nycRef = db.collection("cities").document("NYC")
val sfRef = db.collection("cities").document("SF")
val laRef = db.collection("cities").document("LA")
// Get a new write batch and commit all write operations
db.runBatch { batch ->
// Set the value of 'NYC'
batch.set(nycRef, City())
// Update the population of 'SF'
batch.update(sfRef, "population", 1000000L)
// Delete the city 'LA'
batch.delete(laRef)
}.addOnCompleteListener {
// ...
}
// [END write_batch]
}
private fun getDocument() {
// [START get_document]
val docRef = db.collection("cities").document("SF")
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
Log.d(TAG, "DocumentSnapshot data: ${document.data}")
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
// [END get_document]
}
private fun getDocumentWithOptions() {
// [START get_document_options]
val docRef = db.collection("cities").document("SF")
// Source can be CACHE, SERVER, or DEFAULT.
val source = Source.CACHE
// Get the document, forcing the SDK to use the offline cache
docRef.get(source).addOnCompleteListener { task ->
if (task.isSuccessful) {
// Document found in the offline cache
val document = task.result
Log.d(TAG, "Cached document data: ${document?.data}")
} else {
Log.d(TAG, "Cached get failed: ", task.exception)
}
}
// [END get_document_options]
}
fun customObjects() {
// [START custom_objects]
val docRef = db.collection("cities").document("BJ")
docRef.get().addOnSuccessListener { documentSnapshot ->
val city = documentSnapshot.toObject<City>()
}
// [END custom_objects]
}
private fun listenToDocument() {
// [START listen_document]
val docRef = db.collection("cities").document("SF")
docRef.addSnapshotListener { snapshot, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@addSnapshotListener
}
if (snapshot != null && snapshot.exists()) {
Log.d(TAG, "Current data: ${snapshot.data}")
} else {
Log.d(TAG, "Current data: null")
}
}
// [END listen_document]
}
private fun listenToDocumentLocal() {
// [START listen_document_local]
val docRef = db.collection("cities").document("SF")
docRef.addSnapshotListener { snapshot, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@addSnapshotListener
}
val source = if (snapshot != null && snapshot.metadata.hasPendingWrites()) {
"Local"
} else {
"Server"
}
if (snapshot != null && snapshot.exists()) {
Log.d(TAG, "$source data: ${snapshot.data}")
} else {
Log.d(TAG, "$source data: null")
}
}
// [END listen_document_local]
}
fun listenWithMetadata() {
// [START listen_with_metadata]
// Listen for metadata changes to the document.
val docRef = db.collection("cities").document("SF")
docRef.addSnapshotListener(MetadataChanges.INCLUDE) { snapshot, e ->
// ...
}
// [END listen_with_metadata]
}
private fun getMultipleDocs() {
// [START get_multiple]
db.collection("cities")
.whereEqualTo("capital", true)
.get()
.addOnSuccessListener { documents ->
for (document in documents) {
Log.d(TAG, "${document.id} => ${document.data}")
}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Error getting documents: ", exception)
}
// [END get_multiple]
}
private fun getAllDocs() {
// [START get_multiple_all]
db.collection("cities")
.get()
.addOnSuccessListener { result ->
for (document in result) {
Log.d(TAG, "${document.id} => ${document.data}")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "Error getting documents: ", exception)
}
// [END get_multiple_all]
}
private fun getAllDocsSubcollection() {
// [START firestore_query_subcollection]
db.collection("cities")
.document("SF")
.collection("landmarks")
.get()
.addOnSuccessListener { result ->
for (document in result) {
Log.d(TAG, "${document.id} => ${document.data}")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "Error getting documents: ", exception)
}
// [END firestore_query_subcollection]
}
private fun listenToMultiple() {
// [START listen_multiple]
db.collection("cities")
.whereEqualTo("state", "CA")
.addSnapshotListener { value, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@addSnapshotListener
}
val cities = ArrayList<String>()
for (doc in value!!) {
doc.getString("name")?.let {
cities.add(it)
}
}
Log.d(TAG, "Current cites in CA: $cities")
}
// [END listen_multiple]
}
private fun listenToDiffs() {
// [START listen_diffs]
db.collection("cities")
.whereEqualTo("state", "CA")
.addSnapshotListener { snapshots, e ->
if (e != null) {
Log.w(TAG, "listen:error", e)
return@addSnapshotListener
}
for (dc in snapshots!!.documentChanges) {
when (dc.type) {
DocumentChange.Type.ADDED -> Log.d(TAG, "New city: ${dc.document.data}")
DocumentChange.Type.MODIFIED -> Log.d(TAG, "Modified city: ${dc.document.data}")
DocumentChange.Type.REMOVED -> Log.d(TAG, "Removed city: ${dc.document.data}")
}
}
}
// [END listen_diffs]
}
private fun listenState() {
// [START listen_state]
db.collection("cities")
.whereEqualTo("state", "CA")
.addSnapshotListener { snapshots, e ->
if (e != null) {
Log.w(TAG, "listen:error", e)
return@addSnapshotListener
}
for (dc in snapshots!!.documentChanges) {
if (dc.type == DocumentChange.Type.ADDED) {
Log.d(TAG, "New city: ${dc.document.data}")
}
}
if (!snapshots.metadata.isFromCache) {
Log.d(TAG, "Got initial state.")
}
}
// [END listen_state]
}
private fun detachListener() {
// [START detach_listener]
val query = db.collection("cities")
val registration = query.addSnapshotListener { snapshots, e ->
// ...
}
// ...
// Stop listening to changes
registration.remove()
// [END detach_listener]
}
private fun handleListenErrors() {
// [START handle_listen_errors]
db.collection("cities")
.addSnapshotListener { snapshots, e ->
if (e != null) {
Log.w(TAG, "listen:error", e)
return@addSnapshotListener
}
for (dc in snapshots!!.documentChanges) {
if (dc.type == DocumentChange.Type.ADDED) {
Log.d(TAG, "New city: ${dc.document.data}")
}
}
}
// [END handle_listen_errors]
}
private fun exampleData() {
// [START example_data]
val cities = db.collection("cities")
val data1 = hashMapOf(
"name" to "San Francisco",
"state" to "CA",
"country" to "USA",
"capital" to false,
"population" to 860000,
"regions" to listOf("west_coast", "norcal"),
)
cities.document("SF").set(data1)
val data2 = hashMapOf(
"name" to "Los Angeles",
"state" to "CA",
"country" to "USA",
"capital" to false,
"population" to 3950000,
"regions" to listOf("west_coast", "socal"),
)
cities.document("LA").set(data2)
val data3 = hashMapOf(
"name" to "Washington D.C.",
"state" to null,
"country" to "USA",
"capital" to true,
"population" to 680000,
"regions" to listOf("east_coast"),
)
cities.document("DC").set(data3)
val data4 = hashMapOf(
"name" to "Tokyo",
"state" to null,
"country" to "Japan",
"capital" to true,
"population" to 9500000,
"regions" to listOf("kanto", "honshu"),
)
cities.document("TOK").set(data4)
val data5 = hashMapOf(
"name" to "Beijing",
"state" to null,
"country" to "China",
"capital" to true,
"population" to 21500000,
"regions" to listOf("jingjinji", "hebei"),
)
cities.document("BJ").set(data5)
// [END example_data]
}
fun exampleDataCollectionGroup() {
// [START fs_collection_group_query_data_setup]
val citiesRef = db.collection("cities")
val ggbData = mapOf(
"name" to "Golden Gate Bridge",
"type" to "bridge",
)
citiesRef.document("SF").collection("landmarks").add(ggbData)
val lohData = mapOf(
"name" to "Legion of Honor",
"type" to "museum",
)
citiesRef.document("SF").collection("landmarks").add(lohData)
val gpData = mapOf(
"name" to "Griffth Park",
"type" to "park",
)
citiesRef.document("LA").collection("landmarks").add(gpData)
val tgData = mapOf(
"name" to "The Getty",
"type" to "museum",
)
citiesRef.document("LA").collection("landmarks").add(tgData)
val lmData = mapOf(
"name" to "Lincoln Memorial",
"type" to "memorial",
)
citiesRef.document("DC").collection("landmarks").add(lmData)
val nasaData = mapOf(
"name" to "National Air and Space Museum",
"type" to "museum",
)
citiesRef.document("DC").collection("landmarks").add(nasaData)
val upData = mapOf(
"name" to "Ueno Park",
"type" to "park",
)
citiesRef.document("TOK").collection("landmarks").add(upData)
val nmData = mapOf(
"name" to "National Musuem of Nature and Science",
"type" to "museum",
)
citiesRef.document("TOK").collection("landmarks").add(nmData)
val jpData = mapOf(
"name" to "Jingshan Park",
"type" to "park",
)
citiesRef.document("BJ").collection("landmarks").add(jpData)
val baoData = mapOf(
"name" to "Beijing Ancient Observatory",
"type" to "musuem",
)
citiesRef.document("BJ").collection("landmarks").add(baoData)
// [END fs_collection_group_query_data_setup]
}
private fun simpleQueries() {
// [START simple_queries]
// Create a reference to the cities collection
val citiesRef = db.collection("cities")
// Create a query against the collection.
val query = citiesRef.whereEqualTo("state", "CA")
// [END simple_queries]
// [START simple_query_capital]
val capitalCities = db.collection("cities").whereEqualTo("capital", true)
// [END simple_query_capital]
// [START example_filters]
val stateQuery = citiesRef.whereEqualTo("state", "CA")
val populationQuery = citiesRef.whereLessThan("population", 100000)
val nameQuery = citiesRef.whereGreaterThanOrEqualTo("name", "San Francisco")
// [END example_filters]
// [START simple_query_not_equal]
val notCapitalQuery = citiesRef.whereNotEqualTo("capital", false)
// [END simple_query_not_equal]
}
fun arrayContainsQueries() {
// [START array_contains_filter]
val citiesRef = db.collection("cities")
citiesRef.whereArrayContains("regions", "west_coast")
// [END array_contains_filter]
}
fun arrayContainsAnyQueries() {
// [START array_contains_any_filter]
val citiesRef = db.collection("cities")
citiesRef.whereArrayContainsAny("regions", listOf("west_coast", "east_coast"))
// [END array_contains_any_filter]
}
fun inQueries() {
// [START in_filter]
val citiesRef = db.collection("cities")
citiesRef.whereIn("country", listOf("USA", "Japan"))
// [END in_filter]
// [START not_in_filter]
citiesRef.whereNotIn("country", listOf("USA", "Japan"))
// [END not_in_filter]
// [START in_filter_with_array]
citiesRef.whereIn("regions", listOf(arrayOf("west_coast"), arrayOf("east_coast")))
// [END in_filter_with_array]
}
private fun compoundQueries() {
val citiesRef = db.collection("cities")
// [START chain_filters]
citiesRef.whereEqualTo("state", "CO").whereEqualTo("name", "Denver")
citiesRef.whereEqualTo("state", "CA").whereLessThan("population", 1000000)
// [END chain_filters]
// [START valid_range_filters]
citiesRef.whereGreaterThanOrEqualTo("state", "CA")
.whereLessThanOrEqualTo("state", "IN")
citiesRef.whereEqualTo("state", "CA")
.whereGreaterThan("population", 1000000)
// [END valid_range_filters]
}
private fun compoundQueriesInvalid() {
val citiesRef = db.collection("cities")
// [START invalid_range_filters]
citiesRef.whereGreaterThanOrEqualTo("state", "CA")
.whereGreaterThan("population", 100000)
// [END invalid_range_filters]
}
private fun orderAndLimit() {
val citiesRef = db.collection("cities")
// [START order_and_limit]
citiesRef.orderBy("name").limit(3)
// [END order_and_limit]
// [START order_and_limit_desc]
citiesRef.orderBy("name", Query.Direction.DESCENDING).limit(3)
// [END order_and_limit_desc]
// [START order_by_multiple]
citiesRef.orderBy("state").orderBy("population", Query.Direction.DESCENDING)
// [END order_by_multiple]
// [START filter_and_order]
citiesRef.whereGreaterThan("population", 100000).orderBy("population").limit(2)
// [END filter_and_order]
// [START valid_filter_and_order]
citiesRef.whereGreaterThan("population", 100000).orderBy("population")
// [END valid_filter_and_order]
}
private fun orderAndLimitInvalid() {
val citiesRef = db.collection("cities")
// [START invalid_filter_and_order]
citiesRef.whereGreaterThan("population", 100000).orderBy("country")
// [END invalid_filter_and_order]
}
private fun queryStartAtEndAt() {
// [START query_start_at_single]
// Get all cities with a population >= 1,000,000, ordered by population,
db.collection("cities")
.orderBy("population")
.startAt(1000000)
// [END query_start_at_single]
// [START query_end_at_single]
// Get all cities with a population <= 1,000,000, ordered by population,
db.collection("cities")
.orderBy("population")
.endAt(1000000)
// [END query_end_at_single]
// [START query_start_at_doc_snapshot]
// Get the data for "San Francisco"
db.collection("cities").document("SF")
.get()
.addOnSuccessListener { documentSnapshot ->
// Get all cities with a population bigger than San Francisco.
val biggerThanSf = db.collection("cities")
.orderBy("population")
.startAt(documentSnapshot)
// ...
}
// [END query_start_at_doc_snapshot]
// [START query_pagination]
// Construct query for first 25 cities, ordered by population
val first = db.collection("cities")
.orderBy("population")
.limit(25)
first.get()
.addOnSuccessListener { documentSnapshots ->
// ...
// Get the last visible document
val lastVisible = documentSnapshots.documents[documentSnapshots.size() - 1]
// Construct a new query starting at this document,
// get the next 25 cities.
val next = db.collection("cities")
.orderBy("population")
.startAfter(lastVisible)