在 Firestore 数据库中同时执行 500 多个操作

问题描述 投票:0回答:2

我正在尝试创建一个

WriteBatch
来控制数据库中的一个动态引用。我的应用程序有一个简单的
User-Follow-Post-Feed
模型,我希望我的用户在他的提要中看到他关注的所有用户的帖子。在研究了 Firebase 示例(如 Firefeed )和 Stack Overflow 上的大量帖子之后,我正在做什么。

最佳的想法是保留一条路径(在本例中为

collection
),我在其中存储用户应该在其提要中看到的帖子的
Ids
,这意味着控制复制并删除所有用户的每个帖子他关注/取消关注。

我做了我的

Cloud functions
以原子方式保持这一点,一切都工作正常,但是当我尝试进行大规模测试时,为用户添加了 5000 多个帖子并试图关注他(寻找看看有多少
Cloud function
所花费的时间),我看到批次的操作限制为 500 次。所以我所做的就是将 5000 个 id 分成多个小列表,并为每个列表执行一批,永远不会超过 500 个限制。

但即使这样做,我仍然收到一个错误,

I can't do more than 500 operations in a single commit
,我不知道是否可能是因为批次同时执行,或者为什么。我想也许我可以一个接一个地连接起来,避免一次全部执行。但我仍然遇到一些麻烦。这就是我提问的原因。

这是我的方法:

 fun updateFeedAfterUserfollow(postIds: QuerySnapshot, userId: String) {
        //If there is no posts from the followed user, return
        if (postIds.isEmpty) return
        val listOfPostsId = postIds.map { it.id }
        val mapOfInfo = postIds.map { it.id to it.toObject(PublicUserData::class.java) }.toMap()

        //Get User ref
        val ref = firestore.collection(PRIVATE_USER_DATA).document(userId).collection(FEED)
        //Split the list in multiple list to avoid the max 500 operations per batch
        val idsPartition = Lists.partition(listOfPostsId, 400)

        //Create a batch with max 400 operations and execute it until the whole list have been updated
        idsPartition.forEach { Ids ->
            val batch = firestore.batch().also { batch ->
                Ids.forEach { id -> batch.set(ref.document(id), mapOfInfo[id]!!) }
            }
            batch.commit().addOnCompleteListener {
                if (it.isSuccessful)
                    Grove.d { "Commit updated successfully" }
                else Grove.d { "Commit fail" }
            }
        }
    }
firebase nosql batch-processing google-cloud-functions google-cloud-firestore
2个回答
10
投票

最终导致问题的原因是我试图在事务中实现这种批处理操作,它最终也像批处理一样。这就是为什么即使我为每 400 个引用生成批次,这些实例也是在一个事务内创建的,它就像一个超过 500 个限制的大事务。

我做了一些更改并在我的 GitHub 上的存储库上实现。

//Generate the right amount of batches
    const batches = _.chunk(updateReferences, MAX_BATCH_SIZE)
        .map(dataRefs => {
            const writeBatch = firestoreInstance.batch();
            dataRefs.forEach(ref => {
                writeBatch.update(ref, 'author', newAuthor);
            });
            return writeBatch.commit();
        });

它是用打字稿写的,但你肯定会理解它: https://github.com/FrangSierra/firestore-cloud-functions-typescript/blob/master/functions/src/atomic-operations/index.ts


0
投票

自 2023 年 3 月起,Firestore 不再限制可传递给提交操作或在事务中执行的写入数量()。

© www.soinside.com 2019 - 2024. All rights reserved.