【问题标题】:How to query the Firestore DB properly in Python如何在 Python 中正确查询 Firestore 数据库
【发布时间】:2019-12-11 22:46:15
【问题描述】:

我尝试了多种方法将 .where() 与 firestore 一起使用,最后我只是通过 .where() 并使用 .get() 然后 if/else 语句来检查数据。使用 Javascript 相当简单。 Python 的文档不容易理解。

doc_reffer = db.collection(u'test')
emails = doc_reffer.where(u'adminEmail', u'==', 'x@x.com') \
    .get()
if(emails == True):
    return "is true"
else:
    return "false"

这些都不能正常工作,我得到了响应,但无法检查该对象上的任何内容。 .where() 上可以使用哪些方法,如何正确使用?

doc_reffer = db.collection(u'test')
emails = doc_reffer.where(u'adminEmail', u'==', 'x@x.com')
    return str(emails)

【问题讨论】:

标签: python google-cloud-firestore


【解决方案1】:

使用.stream()方法execute the query

doc_reffer = db.collection(u'test')
emails = doc_reffer.where(u'adminEmail', u'==', 'x@x.com').stream()

for doc in emails:
    print(u'{} => {}'.format(doc.id, doc.to_dict()))

请注意,stream() 返回一个迭代器,并且在您开始迭代结果之前不会获取文档。

您可以获取所有文档,并将它们放入这样的字典中:

doc_reffer = db.collection(u'test').where(u'adminEmail', u'==', 'x@x.com')
emails = [snapshot for snapshot in doc_reffer.stream()]

【讨论】:

  • 谢谢。有没有办法在文档的名称或 ID 上显示 .where ?所以搜索文档名称?我知道我可以使用 doc.id。所以 .where() 文件名 == 'name'
【解决方案2】:

使用 Juan Laras 的答案,我能够成功地获取存在此管理员电子邮件的集合中的所有文档。这就是我想要实现的。我几乎找不到任何文档(简单文档)。

 doc_reffer = db.collection(u'test')
    responseUserEmail = 'x@x.com'
    query = doc_reffer.where(u'adminEmail', u'==', responseUserEmail)
    docs = [snapshot.id for snapshot in query.stream()]
    if responseUserEmail in docs:
        return f'found {responseUserEmail}'
    else:
        return f'did not find {responseUserEmail}'

【讨论】:

    【解决方案3】:

    其他答案似乎正确。您提到使用 python 客户端库不容易理解文档。这是我试图用flask-boiler 解决的问题之一。使用烧瓶锅炉,您将能够像这样查询您的对象:

    emails = [x for x in Test.where(admin_email='x@x.com')]
    for email in emails:
        print(u'{} => {}'.format(email.doc_id, email.to_dict()))
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2019-02-12
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多