如何在Firestore

时间:2017-10-20 12:11:18

标签: java firebase firebase-realtime-database google-cloud-firestore

我正在使用Cloud Firestore并拥有一组文档。对于集合中的每个文档,我想更新其中一个字段。

使用事务执行更新效率很低,因为在更新数据时我不需要读取任何数据。

批量更新似乎是正确的方向,但是文档不包含一次更新多个文档的示例。见这里:Batched Writes

3 个答案:

答案 0 :(得分:7)

如果您使用过Firebase数据库,则无法以原子方式写入完全单独的单独位置,这就是您必须使用批量写入的原因,这意味着要么所有操作都成功,要么都不是应用

关于Firestore,现在所有操作都以原子方式处理。但是,您可以将多个写入操作作为包含set(),update()或delete()操作的任意组合的单个批处理执行。一批写入以原子方式完成,可以写入多个文档。

这是一个关于写入,更新和删除操作的批处理操作的简单示例。

WriteBatch batch = db.batch();

DocumentReference johnRef = db.collection("users").document("John");
batch.set(johnRef, new User());

DocumentReference maryRef = db.collection("users").document("Mary");
batch.update(maryRef, "Anna", 20); //Update name and age

DocumentReference alexRef = db.collection("users").document("Alex");
batch.delete(alexRef);

batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        // ...
    }
});

在批处理对象上调用commit()方法意味着您提交整个批处理。

答案 1 :(得分:1)

我一直在寻找解决方案,但没有找到解决方案,因此,如果有人对此感兴趣,我会制作一个。

public boolean bulkUpdate() {
  try {
    // see https://firebase.google.com/docs/firestore/quotas#writes_and_transactions
    int writeBatchLimit = 500;
    int totalUpdates = 0;

    while (totalUpdates % writeBatchLimit == 0) {
      WriteBatch writeBatch = this.firestoreDB.batch();

      List<QueryDocumentSnapshot> documentsInBatch =
          this.firestoreDB.collection("animals")
              .whereEqualTo("species", "cat")
              .limit(writeBatchLimit)
              .get()
              .get()
              .getDocuments();

      if (documentsInBatch.isEmpty()) {
        break;
      }

      documentsInBatch.forEach(
          document -> writeBatch.update(document.getReference(), "hasTail", true));

      writeBatch.commit().get();

      totalUpdates += documentsInBatch.size();
    }

    System.out.println("Number of updates: " + totalUpdates);

  } catch (Exception e) {
    return false;
  }
  return true;
}

答案 2 :(得分:0)

您可以在SQL中完成

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

WHERE是可选的-因此您可以将所有字段设置为特定值,或者将所有字段设置为选择行,但是不必首先获取对行的引用。

例如,如果内容需要审阅,则可以在审阅列中为所有行设置一个标志。

在Firestore中,我认为没有办法写入集合。

https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference

所有收集方法都是添加文档,获取文档参考-或过滤搜索文档的方法。

据我所知,如果不先获取对文档的引用,就无法更新Firestore中的一组文档。

批处理写入可以加快速度,因为您一次可以更新500个文档。