Python 3.x 如何知道firestore python中是否存在文档?

Python 3.x 如何知道firestore python中是否存在文档?,python-3.x,google-cloud-firestore,Python 3.x,Google Cloud Firestore,我正在使用google.cloud上的firestore库, 是否有任何方法可以检查文档是否存在而不检索所有数据? 我试过了 但它返回404错误。(google.api_core.exceptions.NotFound) 然后我试着 fs.document("path/to/document").exists() 但是“exists”不是DocumentReference中的函数 从源代码中可以看出,exists()是DocumentSnapshot类中的一个函数,函数get()应该返回Doc

我正在使用google.cloud上的firestore库, 是否有任何方法可以检查文档是否存在而不检索所有数据? 我试过了

但它返回404错误。(google.api_core.exceptions.NotFound)

然后我试着

fs.document("path/to/document").exists()
但是“exists”不是DocumentReference中的函数

从源代码中可以看出,exists()是DocumentSnapshot类中的一个函数,函数get()应该返回DocumentSnapshot。我不太确定如何才能获得文档快照


谢谢

您必须检索文档才能知道它是否存在。如果文档存在,它将被视为已读。

如果您使用的是
firebase admin

fs.collection('items').document('item-id').get().exists
True
iff
items/item id
存在

或者

'item-id' in (d.id for d in fs.collection('items').get())
试试这个:

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

使用这种方法,您将检索一个空文档。您将承担“读取”成本,但网络出口将减少,进程的内存使用量几乎为零。

一种更简单、内存效率更高的方法:

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

我在firebase admin v 2.14.0上也遇到了同样的问题,其中
db.collection(“…”).document(“…”).get()
在文档不存在时抛出
google.api_core.exceptions.NotFound:404
。这很奇怪,这似乎是我的服务器上最近出现的问题,在我的macbook安装上运行良好(其中
…get().exists
返回False,没有例外)哦,Firebase内部人士的官方回答。。。感谢您提供了简洁的答案,但是如果不知道文档的内容就知道文档是否存在,这难道不是一个有用的功能吗oThis无法正常处理非常大的集合,因为您必须提取内存中的所有内容!
doc_ref = db.collection('my_collection').document('my_document')
doc = doc_ref.get()
if doc.exists:
    logging.info("Found")
else:
    logging.info("Not found")