Cloud Firestore - 如何检索嵌套子集合的文档信息?

时间:2021-03-31 09:36:58

标签: python google-cloud-firestore web-applications restapi

firestore 数据库的结构如下: 集合:用户 id 为 user_id 的文档 每个文档都有一个子集合:游戏 每个子集合都有 ID 为 game_id 的文档

我的问题是我无法循环遍历第一个集合(---> for user in ref_users:),即使我的 firestore db 已经充满了像我说的那样组织的数据。有人可以帮助我了解如何检索这些文件的信息吗?非常感谢。

from flask import Flask, render_template
from google.cloud import firestore

db = firestore.Client()


@app.route('/', methods=['GET'])
def index():
    ref_users = db.collection(u'users').get()

    games = []
    for user in ref_users:
        print(f'{user.id} => {user.to_dict()}')
        ref_game = db.collection(u'users').document(f'{user.id}').collection(u'games').get()
        for rg in ref_game:
            print(f'{rg.id} => {rg.to_dict()}')
            tmp = rg.to_dict()
            tmp['game_id'] = rg.id
            tmp['user_id'] = user.id
            games.append(tmp)
    return render_template('game_list.html', title='Game list', games=games)

1 个答案:

答案 0 :(得分:0)

在我这边实现了这段代码,做了一些小的改动,并且工作正常。所以我认为您可能正在寻找降低计算复杂性的解决方案。 我认为 collection_group 可能会有所帮助。请检查通用 documentation 和 Python reference

我为与示例相同的结果创建了代码(仅 index 部分)。它少了一个循环:

def index():

    games = []
    ref_game = db.collection_group(u'games').get()
    for rg in ref_game:
        print(f'{rg.id} => {rg.to_dict()}')
        tmp = rg.to_dict()
        tmp['game_id'] = rg.id
        tmp['user_id'] = rg.reference.parent.parent.id
        games.append(tmp)
    return str(games)

我会为此子集合使用更复杂的名称,例如 userGames 或其他名称。这是因为 collection_group 对整个数据库中具有此名称的每个集合都有效。如果您的系统随着增长,您可能会在与此逻辑无关的其他路径中使用相同的名称 games。它将包含在此 collection_group 中并可能导致意外问题。