Getting started with Firestore using Python Python 04.05.2020

The Google Cloud Firestore API is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform.

Mobile apps

Set up your development environment

We are going to use python-firestore as Firestore API client.

Install on Mac/Linux using virtualenv

pip3 install virtualenv
virtualenv <your-env>
source <your-env>/bin/activate
<your-env>/bin/pip3 install google-cloud-firestore

Initialize Cloud Firestore

To use the SDK we’ll need to have a Service Account Key. You can generate this by using Firebase Console > Project Settings. Then selecting Service accounts and clicking Generate new private key. This will produce a .json file with the credentials needed to access the Firebase project.

from google.cloud import firestore

firestore_client = firestore.Client.from_service_account_json('app.json')

ref = firestore_client.collection('users')

Add data

Auto generate document id

doc_ref = ref.document()

Specify document id

doc_ref = ref.document('user1')

Create data

doc_ref.set({
    'first': 'Joe',
    'last': 'Black',
    'born': 1985
})

Update data

doc_ref.update({
    'last': 'Green',
})

Delete

doc_ref.delete()

Read data

doc_ref = ref.document('user1')
doc = doc_ref.get()
if doc.exists:
    print(doc.id, doc.get('first'), doc.to_dict())

Query data

# all
for doc in ref.stream():
    print(u'{} => {}'.format(doc.id, doc.to_dict()))

# limit
users_limit = ref.limit(2)    
docs = users_limit.get()
for doc in docs:
    print(u'Data:{}'.format(doc.to_dict()))

# where

query = ref.where('first', '==', 'Joe').where('born', '>=', 1980)
docs = query.stream()

for doc in docs:
    print(doc.id, doc.get('first'), doc.to_dict())

# order

query = ref.where('born', '>=', 1980).order_by('first')    

# get total row

row_count = len(list(docs))  

Batch update

batch = firestore_client.batch()

for i in range(10):
    data = {
        'first': 'User{}'.format(i),
        'botn': 2000 + i
    }
    row_ref = ref.document()
    batch.set(row_ref, data)

batch.commit()