-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
snippets.py
650 lines (503 loc) · 17.2 KB
/
snippets.py
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
# 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.
import datetime
from google.cloud import firestore
import google.cloud.exceptions
def quickstart_new_instance():
# [START quickstart_new_instance]
from google.cloud import firestore
# Project ID is determined by the GCLOUD_PROJECT environment variable
db = firestore.Client()
# [END quickstart_new_instance]
return db
def quickstart_add_data_one():
db = firestore.Client()
# [START quickstart_add_data_one]
doc_ref = db.collection(u'users').document(u'alovelace')
doc_ref.set({
u'first': u'Ada',
u'last': u'Lovelace',
u'born': 1815
})
# [END quickstart_add_data_one]
def quickstart_add_data_two():
db = firestore.Client()
# [START quickstart_add_data_two]
doc_ref = db.collection(u'users').document(u'aturing')
doc_ref.set({
u'first': u'Alan',
u'middle': u'Mathison',
u'last': u'Turing',
u'born': 1912
})
# [END quickstart_add_data_two]
def quickstart_get_collection():
db = firestore.Client()
# [START quickstart_get_collection]
users_ref = db.collection(u'users')
docs = users_ref.get()
for doc in docs:
print(u'{} => {}'.format(doc.id, doc.to_dict()))
# [END quickstart_get_collection]
def add_from_dict():
db = firestore.Client()
# [START add_from_dict]
data = {
u'name': u'Los Angeles',
u'state': u'CA',
u'country': u'USA'
}
# Add a new doc in collection 'cities' with ID 'LA'
db.collection(u'cities').document(u'LA').set(data)
# [END add_from_dict]
def add_data_types():
db = firestore.Client()
# [START add_data_types]
data = {
u'stringExample': u'Hello, World!',
u'booleanExample': True,
u'numberExample': 3.14159265,
u'dateExample': datetime.datetime.now(),
u'arrayExample': [5, True, u'hello'],
u'nullExample': None,
u'objectExample': {
u'a': 5,
u'b': True
}
}
db.collection(u'data').document(u'one').set(data)
# [END add_data_types]
# [START custom_class_def]
class City(object):
def __init__(self, name, state, country, capital=False, population=0):
self.name = name
self.state = state
self.country = country
self.capital = capital
self.population = population
@staticmethod
def from_dict(source):
# [START_EXCLUDE]
city = City(source[u'name'], source[u'state'], source[u'country'])
if u'capital' in source:
city.capital = source[u'capital']
if u'population' in source:
city.population = source[u'population']
return city
# [END_EXCLUDE]
def to_dict(self):
# [START_EXCLUDE]
dest = {
u'name': self.name,
u'state': self.state,
u'country': self.country
}
if self.capital:
dest[u'capital'] = self.capital
if self.population:
dest[u'population'] = self.population
return dest
# [END_EXCLUDE]
def __repr__(self):
return u'City(name={}, country={}, population={}, capital={})'.format(
self.name, self.country, self.population, self.capital)
# [END custom_class_def]
def add_example_data():
db = firestore.Client()
# [START add_example_data]
cities_ref = db.collection(u'cities')
cities_ref.document(u'SF').set(
City(u'San Francisco', u'CA', u'USA', False, 860000).to_dict())
cities_ref.document(u'LA').set(
City(u'Los Angeles', u'CA', u'USA', False, 3900000).to_dict())
cities_ref.document(u'DC').set(
City(u'Washington D.C.', None, u'USA', True, 680000).to_dict())
cities_ref.document(u'TOK').set(
City(u'Tokyo', None, u'Japan', True, 9000000).to_dict())
cities_ref.document(u'BJ').set(
City(u'Beijing', None, u'China', True, 21500000).to_dict())
# [END add_example_data]
def add_custom_class_with_id():
db = firestore.Client()
# [START add_custom_class_with_id]
city = City(name=u'Los Angeles', state=u'CA', country=u'USA')
db.collection(u'cities').document(u'LA').set(city.to_dict())
# [END add_custom_class_with_id]
def add_data_with_id():
db = firestore.Client()
data = {}
# [START add_data_with_id]
db.collection(u'cities').document(u'new-city-id').set(data)
# [END add_data_with_id]
def add_custom_class_generated_id():
db = firestore.Client()
# [START add_custom_class_generated_id]
city = City(name=u'Tokyo', state=None, country=u'Japan')
db.collection(u'cities').add(city.to_dict())
# [END add_custom_class_generated_id]
def add_new_doc():
db = firestore.Client()
# [START add_new_doc]
new_city_ref = db.collection(u'cities').document()
# later...
new_city_ref.set({
# ...
})
# [END add_new_doc]
def get_check_exists():
db = firestore.Client()
# [START get_check_exists]
doc_ref = db.collection(u'cities').document(u'SF')
try:
doc = doc_ref.get()
print(u'Document data: {}'.format(doc.to_dict()))
except google.cloud.exceptions.NotFound:
print(u'No such document!')
# [END get_check_exists]
def get_custom_class():
db = firestore.Client()
# [START get_custom_class]
doc_ref = db.collection(u'cities').document(u'BJ')
doc = doc_ref.get()
city = City.from_dict(doc.to_dict())
print(city)
# [END get_custom_class]
def get_simple_query():
db = firestore.Client()
# [START get_simple_query]
docs = db.collection(u'cities').where(u'capital', u'==', True).get()
for doc in docs:
print(u'{} => {}'.format(doc.id, doc.to_dict()))
# [END get_simple_query]
def get_full_collection():
db = firestore.Client()
# [START get_full_collection]
docs = db.collection(u'cities').get()
for doc in docs:
print(u'{} => {}'.format(doc.id, doc.to_dict()))
# [END get_full_collection]
def structure_doc_ref():
db = firestore.Client()
# [START structure_doc_ref]
a_lovelace_ref = db.collection(u'users').document(u'alovelace')
# [END structure_doc_ref]
print(a_lovelace_ref)
def structure_collection_ref():
db = firestore.Client()
# [START structure_collection_ref]
users_ref = db.collection(u'users')
# [END structure_collection_ref]
print(users_ref)
def structure_doc_ref_alternate():
db = firestore.Client()
# [START structure_doc_ref_alternate]
a_lovelace_ref = db.document(u'users/alovelace')
# [END structure_doc_ref_alternate]
return a_lovelace_ref
def structure_subcollection_ref():
db = firestore.Client()
# [START structure_subcollection_ref]
room_a_ref = db.collection(u'rooms').document(u'roomA')
message_ref = room_a_ref.collection(u'messages').document(u'message1')
# [END structure_subcollection_ref]
print(message_ref)
def update_doc():
db = firestore.Client()
# [START update_doc]
city_ref = db.collection(u'cities').document(u'DC')
# Set the capital field
city_ref.update({u'capital': True})
# [END update_doc]
def update_multiple():
db = firestore.Client()
# [START update_multiple]
doc_ref = db.collection(u'cities').document(u'DC')
doc_ref.update({
u'name': u'Washington D.C.',
u'country': u'USA',
u'capital': True
})
# [END update_multiple]
def update_create_if_missing():
db = firestore.Client()
# [START update_create_if_missing]
city_ref = db.collection(u'cities').document(u'BJ')
city_ref.update({
u'capital': True
}, firestore.CreateIfMissingOption(True))
# [END update_create_if_missing]
def update_nested():
db = firestore.Client()
# [START update_nested]
# Create an initial document to update
frank_ref = db.collection(u'users').document(u'frank')
frank_ref.set({
u'name': u'Frank',
u'favorites': {
u'food': u'Pizza',
u'color': u'Blue',
u'subject': u'Recess'
},
u'age': 12
})
# Update age and favorite color
frank_ref.update({
u'age': 13,
u'favorites.color': u'Red'
})
# [END update_nested]
def update_server_timestamp():
db = firestore.Client()
# [START update_server_timestamp]
city_ref = db.collection(u'objects').document(u'some-id')
city_ref.update({
u'timestamp': firestore.SERVER_TIMESTAMP
})
# [END update_server_timestamp]
def update_data_transaction():
db = firestore.Client()
# [START update_data_transaction]
transaction = db.transaction()
city_ref = db.collection(u'cities').document(u'SF')
@firestore.transactional
def update_in_transaction(transaction, city_ref):
snapshot = city_ref.get(transaction=transaction)
transaction.update(city_ref, {
u'population': snapshot.get(u'population') + 1
})
update_in_transaction(transaction, city_ref)
# [END update_data_transaction]
def update_data_transaction_result():
db = firestore.Client()
# [START update_data_transaction_result]
transaction = db.transaction()
city_ref = db.collection(u'cities').document(u'SF')
@firestore.transactional
def update_in_transaction(transaction, city_ref):
snapshot = city_ref.get(transaction=transaction)
new_population = snapshot.get(u'population') + 1
if new_population < 1000000:
transaction.update(city_ref, {
u'population': new_population
})
return True
else:
return False
result = update_in_transaction(transaction, city_ref)
if result:
print(u'Population updated')
else:
print(u'Sorry! Population is too big.')
# [END update_data_transaction_result]
def update_data_batch():
db = firestore.Client()
# [START update_data_batch]
batch = db.batch()
# Set the data for NYC
nyc_ref = db.collection(u'cities').document(u'NYC')
batch.set(nyc_ref, {u'name': u'New York City'})
# Update the population for SF
sf_ref = db.collection(u'cities').document(u'SF')
batch.update(sf_ref, {u'population': 1000000})
# Delete LA
la_ref = db.collection(u'cities').document(u'LA')
batch.delete(la_ref)
# Commit the batch
batch.commit()
# [END update_data_batch]
def compound_query_example():
db = firestore.Client()
# [START compound_query_example]
# Create a reference to the cities collection
cities_ref = db.collection(u'cities')
# Create a query against the collection
query_ref = cities_ref.where(u'state', u'==', u'CA')
# [END compound_query_example]
return query_ref
def compound_query_simple():
db = firestore.Client()
# [START compound_query_simple]
cities_ref = db.collection(u'cities')
query = cities_ref.where(u'capital', u'==', True)
# [END compound_query_simple]
print(query)
def compound_query_single_clause():
db = firestore.Client()
# [START compound_query_single_clause]
cities_ref = db.collection(u'cities')
cities_ref.where(u'state', u'==', u'CA')
cities_ref.where(u'population', u'<', 1000000)
cities_ref.where(u'name', u'>=', u'San Francisco')
# [END compound_query_single_clause]
def compound_query_valid_multi_clause():
db = firestore.Client()
# [START compound_query_valid_multi_clause]
cities_ref = db.collection(u'cities')
sydney_query = cities_ref.where(
u'state', u'==', u'CO').where(u'name', u'==', u'Denver')
large_us_cities_query = cities_ref.where(
u'state', u'==', u'CA').where(u'population', u'>', 1000000)
# [END compound_query_valid_multi_clause]
print(sydney_query)
print(large_us_cities_query)
def compound_query_valid_single_field():
db = firestore.Client()
# [START compound_query_valid_single_field]
cities_ref = db.collection(u'cities')
cities_ref.where(u'state', u'>=', u'CA').where(u'state', u'<=', u'IN')
# [END compound_query_valid_single_field]
def compound_query_invalid_multi_field():
db = firestore.Client()
# [START compound_query_invalid_multi_field]
cities_ref = db.collection(u'cities')
cities_ref.where(
u'state', u'>=', u'CA').where(u'population', u'>=', 1000000)
# [END compound_query_invalid_multi_field]
def order_simple_limit():
db = firestore.Client()
# [START order_simple_limit]
db.collection(u'cities').order_by(u'name').limit(3).get()
# [END order_simple_limit]
def order_simple_limit_desc():
db = firestore.Client()
# [START order_simple_limit_desc]
cities_ref = db.collection(u'cities')
query = cities_ref.order_by(
u'name', direction=firestore.Query.DESCENDING).limit(3)
results = query.get()
# [END order_simple_limit_desc]
print(results)
def order_multiple():
db = firestore.Client()
# [START order_multiple]
cities_ref = db.collection(u'cities')
cities_ref.order_by(u'state').order_by(
u'population', direction=firestore.Query.DESCENDING)
# [END order_multiple]
def order_where_limit():
db = firestore.Client()
# [START order_where_limit]
cities_ref = db.collection(u'cities')
query = cities_ref.where(
u'population', u'>', 2500000).order_by(u'population').limit(2)
results = query.get()
# [END order_where_limit]
print(results)
def order_where_valid():
db = firestore.Client()
# [START order_where_valid]
cities_ref = db.collection(u'cities')
query = cities_ref.where(
u'population', u'>', 2500000).order_by(u'population')
results = query.get()
# [END order_where_valid]
print(results)
def order_where_invalid():
db = firestore.Client()
# [START order_where_invalid]
cities_ref = db.collection(u'cities')
query = cities_ref.where(u'population', u'>', 2500000).order_by(u'country')
results = query.get()
# [END order_where_invalid]
print(results)
def cursor_simple_start_at():
db = firestore.Client()
# [START cursor_simple_start_at]
cities_ref = db.collection(u'cities')
query_start_at = cities_ref.order_by(u'population').start_at({
u'population': 1000000
})
# [END cursor_simple_start_at]
return query_start_at
def cursor_simple_end_at():
db = firestore.Client()
# [START cursor_simple_end_at]
cities_ref = db.collection(u'cities')
query_end_at = cities_ref.order_by(u'population').end_at({
u'population': 1000000
})
# [END cursor_simple_end_at]
return query_end_at
def cursor_paginate():
db = firestore.Client()
# [START cursor_paginate]
cities_ref = db.collection(u'cities')
first_query = cities_ref.order_by(u'population').limit(3)
# Get the last document from the results
docs = first_query.get()
last_doc = list(docs)[-1]
# Construct a new query starting at this document
# Note: this will not have the desired effect if
# multiple cities have the exact same population value
last_pop = last_doc.to_dict()[u'population']
next_query = (
cities_ref
.order_by(u'population')
.start_after({
u'population': last_pop
})
.limit(3)
)
# Use the query for pagination
# ...
# [END cursor_paginate]
return next_query
def cursor_multiple_conditions():
db = firestore.Client()
# [START cursor_multiple_conditions]
start_at_name = (
db.collection(u'cities')
.order_by(u'name')
.order_by(u'state')
.start_at({
u'name': u'Springfield'
})
)
start_at_name_and_state = (
db.collection(u'cities')
.order_by(u'name')
.order_by(u'state')
.start_at({
u'name': u'Springfield',
u'state': u'Missouri'
})
)
# [END cursor_multiple_conditions]
return start_at_name, start_at_name_and_state
def delete_single_doc():
db = firestore.Client()
# [START delete_single_doc]
db.collection(u'cities').document(u'DC').delete()
# [END delete_single_doc]
def delete_field():
db = firestore.Client()
# [START delete_field]
city_ref = db.collection(u'cities').document(u'BJ')
city_ref.update({
u'capital': firestore.DELETE_FIELD
})
# [END delete_field]
def delete_full_collection():
db = firestore.Client()
# [START delete_full_collection]
def delete_collection(coll_ref, batch_size):
docs = coll_ref.limit(10).get()
deleted = 0
for doc in docs:
print(u'Deleting doc {} => {}'.format(doc.id, doc.to_dict()))
doc.reference.delete()
deleted = deleted + 1
if deleted >= batch_size:
return delete_collection(coll_ref, batch_size)
# [END delete_full_collection]
delete_collection(db.collection(u'cities'), 10)