Firestore 集合 - recursiveDelete() 与批量删除

Firestore Collections - recursiveDelete() vs batched deletions

删除 Firestore 集合时,什么被认为最有效?

使用批处理执行删除:

async function deleteCollection(db, collectionPath, batchSize) {
  const collectionRef = db.collection(collectionPath);
  const query = collectionRef.orderBy('__name__').limit(batchSize);

  return new Promise((resolve, reject) => {
    deleteQueryBatch(db, query, resolve).catch(reject);
  });
}

async function deleteQueryBatch(db, query, resolve) {
  const snapshot = await query.get();

  const batchSize = snapshot.size;
  if (batchSize === 0) {
    // When there are no documents left, we are done
    resolve();
    return;
  }

  // Delete documents in a batch
  const batch = db.batch();
  snapshot.docs.forEach((doc) => {
    batch.delete(doc.ref);
  });
  await batch.commit();

  // Recurse on the next process tick, to avoid
  // exploding the stack.
  process.nextTick(() => {
    deleteQueryBatch(db, query, resolve);
  });
}

或使用 firestore 的默认 recursiveDelete() 方法:

await firestore.recursiveDelete(collectionRef);

注意:我要删除的集合没有嵌套的子集合。另外,我是运行云函数中的这段代码。

/messages (C)
  -message_id_1 (D)
  -message_id_2 (D)
  -message_id_3 (D)
  ...
  -message_id_10000 (D)

recursiveDelete 函数使用与后台批处理写入相同的机制,因此任何性能差异都可以忽略不计。