Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if document exists in firestore python?

im using the firestore library from google.cloud, is there any way to check if a document exists without retrieven all the data? i tried

fs.document("path/to/document").get().exists()

but it returns a 404 error. (google.api_core.exceptions.NotFound)

then i tried

fs.document("path/to/document").exists()

but "exists" isn't a function from DocumentReference.

I can see from the source that exists() is a function from the DocumentSnapshot Class, and the function get() should return a documentSnapshot. i'm not very sure how else i can get a DocumentSnapshot

Thank you

like image 969
Cristóbal Felipe Fica Urzúa Avatar asked Jul 23 '18 16:07

Cristóbal Felipe Fica Urzúa


People also ask

How do I find out how many documents are in my firestore collection?

If you need a count, just use the collection path and prefix it with counters . As this approach uses a single database and document, it is limited to the Firestore constraint of 1 Update per Second for each counter.

How do you check data on firestore?

Cloud Firestore doesn't support native indexing or search for text fields in documents. Additionally, downloading an entire collection to search for fields client-side isn't practical. To enable full text search of your Cloud Firestore data, use a dedicated third-party search service.

Does firestore Create collection if not exists?

Collections and documents are created implicitly in Cloud Firestore. Simply assign data to a document within a collection. If either the collection or document does not exist, Cloud Firestore creates it.


1 Answers

A much simpler and memory efficient approach:

doc_ref = db.collection('my_collection').document('my_document')
doc = doc_ref.get()
if doc.exists:
    logging.info("Found")
else:
    logging.info("Not found")

Source

like image 135
Nebulastic Avatar answered Sep 19 '22 14:09

Nebulastic