2

我试图创建一个WriteBatch来保持我的数据库中的某个引用的控制权。我的应用有一个简单的User-Follow-Post-Feed模型,我希望我的用户在他的Feed中看到他所关注的所有用户的帖子。我在研究Firebase示例(如Firefeed)以及StackOverflow上的很多帖子之后正在做什么。在Firestore数据库中一次执行500多个操作

最佳的想法是保持一个路径(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" } 
      } 
     } 
    } 

希望有人可以给我一只手。 非常感谢你的时间!

+0

什么是你的错误信息? –

+0

你的最终解决方案是什么? – 22Ryann

回答

1

最后这个问题是由于我试图在一个事务中实现这个批处理操作而引起的,这个操作在最后也像批处理一样。这就是为什么即使我为每个引用生成批次,这些实例都是在一个事务内部创建的,并且它像一个超过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

相关问题