猿问

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

我正在通过python中的网络抓取创建文档并将它们上传到Firestore。为此,我将它们添加到字典中,并从 Python 中的 for 循环中逐个上传它们(理想情况下最好一次上传集合,但这似乎不是一种选择)。我想使用批次,但是它们每批次有 500 个限制,我需要执行超过 100,000 次操作。这些操作仅仅是set()操作和一些操作,update() 是否有一个函数可以知道批处理的当前大小,以便我可以重新初始化它?在 python 中使用批处理进行 500 多个操作的最佳方法是什么?


湖上湖
浏览 204回答 2
2回答

呼唤远方

Batch 中的最大操作数为 500。如果您需要更多操作,则需要多个批处理。没有 API 可以确定 Batch 中的当前操作数。如果你需要它,你将不得不自己跟踪它。

芜湖不芜

我发现在使用 python 时处理 500 批限制的最佳方法是将我想要发送到 Firestore 的所有数据放在“平面”字典中,这样我就可以处理每个唯一的文档。该字典将每个文档的键作为以下形式:“collection_document_collection_document...”,而该键的值将是具有以下内容的字典:{'action': 'set', 'reference': reference, 'document': {}}'action' 可以是 'set'、'update' 或 'delete','reference' 键是实际的 Firestore 引用,而 'document' 只是文档。例如,这是位于不同位置的 2 个文档。{    '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 个项目的数组,然后使用批处理的“操作”键将所有这些项目添加到批处理中。# Convert dictionary to a listdictionary_list = []for item in dictionary:    dictionary_list.append(dictionary.get(item))# Split List in lists containing 500 items per listlist_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 loopfor 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()在我处理完我需要的所有数据后的特殊情况下,我最终进行了超过 700,000 次操作,因此请注意计费:-D
随时随地看视频慕课网APP

相关分类

Python
我要回答