芜湖不芜
我发现在使用 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