如何在python中为firestore批处理500多个操作?

如何在python中为firestore批处理500多个操作?,python,firebase,google-cloud-firestore,Python,Firebase,Google Cloud Firestore,我正在用python从网页抓取创建文档,并将它们上传到Firestore。 为此,我将它们添加到一个字典中,并从python中的for循环中一个接一个地上传它们(最好是立即上传集合,但这似乎不是一个选项)。我想使用批次,但是每个批次有500个限制,我需要执行100000多个操作。这些操作仅仅是set()操作和几个update() 是否有一个函数可以知道批处理的当前大小,以便我可以重新初始化它? 在python中,对500多个操作使用批处理的最佳方式是什么?批处理中的最大操作数是500。如果需要更

我正在用python从网页抓取创建文档,并将它们上传到Firestore。 为此,我将它们添加到一个字典中,并从python中的for循环中一个接一个地上传它们(最好是立即上传集合,但这似乎不是一个选项)。我想使用批次,但是每个批次有500个限制,我需要执行100000多个操作。这些操作仅仅是
set()
操作和几个
update()
是否有一个函数可以知道批处理的当前大小,以便我可以重新初始化它?
在python中,对500多个操作使用批处理的最佳方式是什么?

批处理中的最大操作数是500。如果需要更多操作,则需要多个批次


没有用于确定批处理中当前操作数的API。如果您需要,您必须自己跟踪它。

在使用python时,我发现处理500个批次限制的最佳方法是将我要发送到Firestore的所有数据放在一个“平面”字典中,这样我就可以处理每个独特的文档。对于每个文档,此词典都具有“collection\u document\u collection\u document…”形式的as键,而该键的值将是一个具有以下内容的词典:

{'action': 'set', 'reference': reference, 'document': {}}
“操作”可以是“设置”、“更新”或“删除”,“引用”键是实际的Firestore引用,“文档”就是文档。 例如,这是位于不同位置的两个文档

{
    'user_data_roger':
    {'action': 'set', 'reference': db.collection('user_data').document('roger'), 'document': {'name': 'Roger', 'age': 37}},
    'user_data_roger_works_april':
    {'action': 'update', 'reference': db.collection('user_data').document('roger').collection('works').document('april'), 'document': {'is_valid': True, 'in_progress': True, 'level':5}},
}
处理完所有需要的数据后,我想将字典拆分为500个项目的数组,然后使用批处理的“action”键将所有这些项目添加到批处理中

# Convert dictionary to a list
dictionary_list = []
for item in dictionary:
    dictionary_list.append(dictionary.get(item))
# Split List in lists containing 500 items per list
list_to_batch = [dictionary_list[item:item+500] for item in range(0, len(dictionary_list), 500)]
# Finally iterate through the 'list_to_batch' add each item to the batch and commit using a for loop
for item in list_to_batch:
    batch = db.batch()
    for document in item:
        if document['action'] == 'set':
            batch.set(document['reference'], document['value'])
        elif draw['action'] == 'update':
            batch.update(document['reference'], document['value'])
        else:
            batch.delete(document['reference'], document['value'])
    # Finally commit the batch
    batch.commit()
在我的特殊情况下,在处理完所有需要的数据后,我完成了超过700000次操作,因此请注意账单:-D