如何知道firestore python中是否存在文档?

0lvr5msh  于 3个月前  发布在  Python
关注(0)|答案(4)|浏览(107)

我使用的firestore库从google.cloud,有没有什么办法来检查,如果一个文件存在,而不retrieven所有的数据?

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

字符串
但是它返回一个404错误。(google.API_core.exceptions.NotFound)
然后我试

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


但“exists”不是DocumentReference中的函数。
我可以从源代码中看到exists()是DocumentSnapshot类中的一个函数,函数get()应该返回一个documentSnapshot。
谢谢你

bn31dyow

bn31dyow1#

试试这个:

docRef      = db.collection('collectionName').document('documentID')
docSnapshot = docRef.get([]); # Empty array for fields to get
isExists    = docSnapshot.exists

字符串
使用这种方法,您将检索一个空文档。您将产生“读取”成本,但将减少网络出口,并且进程的使用内存几乎为零。

qgelzfjb

qgelzfjb2#

您必须检索文档以了解它是否存在。如果文档存在,则将其视为已读。

yi0zb3m4

yi0zb3m43#

一个更简单和内存有效的方法:

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

ih99xse1

ih99xse14#

如果你使用firebase-admin

fs.collection('items').document('item-id').get().exists

字符串
True当且仅当items/item-id存在
替代地

'item-id' in (d.id for d in fs.collection('items').get())

相关问题