【问题标题】:Issue with firestore 500 writes in a batch limit批量限制中的 firestore 500 写入问题
【发布时间】:2020-04-08 14:28:55
【问题描述】:

我允许导入数据,这让我可以在 Firestore 中写入大量文档。我有一个文件柜台,所以我不得不放慢写的速度。

// process 75 contacts every 1200ms
return new Promise<boolean>(async (resolve, reject) => {
      timer(0, 1200)
        .pipe(
          takeWhile((_) => !!contacts.length),
        )
        .subscribe(async () => {
          const next = contacts.splice(0, 75);
          await updateContacts(userId, next);
        });
    });

更新联系人的工作方式如下:-

// It updates three documents: Basic, Extended and the User doc
// which has the count
export async function updateContacts(userId: string, contacts: Contact[]) {
  const firestore = admin.firestore();
  const batch = firestore.batch();
  const userRef = getUserRef(userId);

  for (const contact of contacts) {
    const basicRef = getBasicContactRef(userId);
    const extendedRef = getDetailContactRef(userId, basicRef.id);

    const basic = contact.getBasic();
    batch.set(basicRef, {
      ...basic,
      ...{ timestamp: FieldValue.serverTimestamp() },
    });

    const extended = contact.getExtended();
    batch.set(extendedRef, {
      ...extended,
      ...{ timestamp: FieldValue.serverTimestamp() },
    });

  }

  // Now update the count
  batch.update(userRef, {
    numberOfContacts: FieldValue.increment(contacts.length),
  });

  // commit it all
  return batch.commit();
}

但是,当我使用大量联系人运行它时,它会失败并显示以下内容:-

错误:3 INVALID_ARGUMENT:每个请求最多允许 500 次写入

我以为每个请求的写入次数少于 500 次!

我真的很想弄清楚。我不是太聪明,所以请教各位聪明人。知道我做错了什么吗?

【问题讨论】:

  • 如果我没记错的话,根据您正在执行的确切操作,有效限制可能会更低。因此,我通常可以在大约 200-250 次写入时批量处理。让我看看能不能找到那个链接。

标签: firebase google-cloud-firestore


【解决方案1】:

我有一种预感,问题在于您的代码应用于字段的字段转换。 500 的限制是基于 mutations 的数量而不是顶级文档操作。我查看了将批量更新/设置操作转换为突变的内部代码,在某些情况下存在加倍因素:

https://github.com/firebase/firebase-js-sdk/blob/9bc4167d5895099ff60fd75d462cbb0d9fd8429e/packages/firestore/src/api/user_data_reader.ts#L101

所以您可能会看到您的批次 75 为 batch.set(basicRef) 产生至少 2 个突变,为 batch.set(extendedRef) 产生额外的 2 个突变等。我可能还有一些其他隐藏成本尚未追踪到将总突变数增加到 > 500。

是否可以减少传递给 updateContacts() 的文档(联系人)的数量?

【讨论】:

  • 确实如此。谢谢瓦迪姆!
猜你喜欢
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2021-10-12
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
  • 2018-03-19
相关资源
最近更新 更多