firebase 如何使用Python API了解Firestore中的集合

falq053o  于 2023-04-22  发布在  Python
关注(0)|答案(4)|浏览(156)

我正在使用Python从客户端连接到一个firestore数据库。
问题是我不知道如何查看他在数据库中的收藏:

from google.cloud import firestore
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

cred = credentials.Certificate('credentials/credentials.json')
app = firebase_admin.initialize_app(cred)

db = firestore.client()

users_ref = db.collection(u'name_of_colection')
docs = users_ref.stream()

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

我一直在寻找如何得到的名称的集合,他有,但我没有找到任何东西,这是有用的我。我也尝试了这一点:

cols = db.collections()
list_col = []
for col in cols:
    list_col.append(col)

len(list_col)

得到len = 6
然后,我对我生成的列表中的不同col执行了以下操作:

docs = list_col[5].stream()

data = []

for doc in docs:
    data.append(doc.to_dict())
print(data)

这个数据打印出一个有键和值的字典,但我不知道只得到一个有集合名称的列表,

laawzig2

laawzig21#

我认为您必须从每个集合中获取id(即您正在谈论的collection name

list_col = []
for col in collections:
    list_col.append(col.id) // <-- add this please
print(list_col)

希望对你有帮助

flvtvl50

flvtvl502#

简单的解决方案:

import firebase_admin
from firebase_admin import firestore

app_options = {'projectId': 'test-project'}
default_app = firebase_admin.initialize_app(options=app_options)

db = firestore.client()
collection = db.collections()
list_col = []
for col in collection:
    list_col.append(col.id)
print(list_col)
qvtsj1bj

qvtsj1bj3#

我不敢相信在互联网上找到问题How to list all collections in Firestore in Python?的答案有多难。现在,整合其他人发布的答案,这里是最小的代码:

from google.cloud import firestore

db = firestore.Client()

# The following call returns a Python Generator
#     https://github.com/googleapis/python-firestore/blob/532aff8d7b5bfde8b73be6b7e508f9d9fd6b5254/google/cloud/firestore_v1/client.py#L271-L297
cols = db.collections()

for c in cols:
    print(c.id)

令人惊讶的是,看似广泛的官方GCP Firestore code samples(或its corresponding Github snippets)没有这样的例子。
这真的不应该是一个很难找到的答案。

ssm49v7z

ssm49v7z4#

您在fire base中看到的任何集合都取决于您的权限。您可以使用

query = client.collection_group('mygroup')
or 
query = client.collections()

它给出了顶层层次结构,你必须运行多次才能找到最低的文档级别。

query = client.collection_group('mygroup')
@param {string} collectionId Identifies the collections to query over. Every collection or subcollection with this ID as the last segment of its path will be included. Cannot contain a slash. @returns {Query} The created Query.

collections()[source]
List top-level collections of the client’s database.

Returns
iterator of subcollections of the current document.

Return type
Sequence[CollectionReference]

相关问题