← 中文资源

简体中文版本

Firebase Firestore 批量原子写入

用 Admin SDK 的批量写实现多文档原子变更:单批不超官方上限、超量自动分批提交、serverTimestamp 统一写入时钟。

阅读英文原文

示例说明

逐条 set 九百次既慢又可能中途失败留下一半数据。批量写把多个文档变更打包成一次原子提交:全成或全败,无中间态。Firestore 的单批上限是五百个操作,导入脚本按四百五切批留安全余量;serverTimestamp 把写入时间交给服务端时钟,避免多机时钟偏差让排序失真。

技术要点

  • 批量提交保证多文档原子性
  • 按上限切批处理超大规模导入
  • serverTimestamp 消除客户端时钟偏差

代码解读

importProducts 循环里把每个商品的 set 追加进当前批次,计数达到四百五就提交并开启新批次,循环结束的尾巴批次单独提交。FieldValue.serverTimestamp 作为字段值写入时是占位符,服务端落库时替换为真实时间。最后读取验证数据可见。

使用建议

批次内文档间不能有读依赖,需要读的拆到下一批。导入与业务写入并发时注意集合索引压力。服务账号凭据从环境注入,泄漏等于全域失守。

代码示例

import { initializeApp, cert } from 'firebase-admin/app';
import { getFirestore, WriteBatch } from 'firebase-admin/firestore';

const app = initializeApp({
  credential: cert(JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT ?? '{}')),
});
const db = getFirestore(app);

const MAX_BATCH = 450; // 官方上限 500,留出余量

async function importProducts(products) {
  let batch: WriteBatch = db.batch();
  let pending = 0;

  for (const product of products) {
    const ref = db.collection('products').doc(product.sku);
    batch.set(ref, {
      title: product.title,
      price: product.price,
      updatedAt: FieldValue.serverTimestamp(),
    });
    pending += 1;

    if (pending >= MAX_BATCH) {
      await batch.commit();
      batch = db.batch();
      pending = 0;
    }
  }

  if (pending > 0) await batch.commit();
}

const products = Array.from({ length: 920 }, (_, i) => ({
  sku: 'SKU-' + i,
  title: 'Product ' + i,
  price: (i % 50) * 3 + 5,
}));

await importProducts(products);

const snapshot = await db.collection('products').limit(3).get();
console.log('imported docs visible:', snapshot.size);
await app.delete?.();