【问题标题】:How to know if document exists in firestore python?如何知道firestore python中是否存在文档?
【发布时间】:2018-12-31 04:01:41
【问题描述】:

我正在使用来自 google.cloud 的 firestore 库, 有没有办法在不检索所有数据的情况下检查文档是否存在? 我试过了

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

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

然后我尝试了

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

但“存在”不是 DocumentReference 中的函数。

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

谢谢

【问题讨论】:

  • 我在 firebase admin v 2.14.0 上遇到了同样的问题,当文档不存在时,db.collection('...').document('...').get() 会抛出 google.api_core.exceptions.NotFound: 404。很奇怪,这似乎是我服务器上最近出现的问题,并且在我的 macbook 安装上运行良好(....get().exists 无一例外地返回 False)

标签: python-3.x google-cloud-firestore


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您使用的是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())
    

    【讨论】:

    • 这不适用于非常大的集合,因为您必须将所有内容都拉到内存中!
    【解决方案3】:

    试试这个:

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

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 哦,来自 Firebase 内部人员的官方回答...感谢您的简洁回答,但是在不知道其内容的情况下知道文档是否存在不是一个有用的功能吗? :o
      猜你喜欢
      • 1970-01-01
      • 2021-07-22
      • 2021-11-25
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 2018-11-10
      • 2016-02-25
      • 2019-01-09
      相关资源
      最近更新 更多