Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: Update multiple objects in single transaction

Tags:

java

firebase

I have found some thread below which talk about this scenario.

  • Firebase: How do I update multiple resources atomically
  • Firebase data consistency across multiple nodes
  • How to store users and groups for a chat using Firebase

However still struggling to find, if there are any recommended data structure design for this. I see a Multi-write library firebase-multi-write which says you probably don't need this in most cases.

But I think I do need this, my scenario is : 3 users

/users/A : {credit:20}

/users/B : {credit:3}

/users/C :  {credit:10}

And each user can steal credits from each other all at the same time.,

  • A steals from B credits look like {21, 2}
  • B steals from C credits look like {3, 9}
  • C steals from A credits look like {11, 20}

Now I need to update the credits for each user to maintain this consistency, so that each steal operation is atomic in nature.

What will be the best way to handle such scenario, while maintaining data integrity in Java?

like image 594
duskandawn Avatar asked Jul 20 '15 21:07

duskandawn


People also ask

What is the maximum documents that are write by per transaction or batch of write in cloud firestore?

Each transaction or batch of writes can write to a maximum of 500 documents.

What is a Subcollection in firebase?

A subcollection is a collection associated with a specific document. Note: You can query across subcollections with the same collection ID by using Collection Group Queries. You can create a subcollection called messages for every room document in your rooms collection: collections_bookmark rooms. class roomA.


1 Answers

In setember/2015 firebase developers released new version.

With this release, you can now do this in a single atomic update to both locations:

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
// Generate a new push ID for the new post

Firebase newPostRef = ref.child("posts").push();
String newPostKey = newPostRef.getKey();

// Create the data we want to update
Map newPost = new HashMap();
newPost.put("title", "New Post");
newPost.put("content", "Here is my new post!");

Map updatedUserData = new HashMap();
updatedUserData.put("users/posts/" + newPostKey, true);
updatedUserData.put("posts/" + newPostKey, newPost);

// Do a deep-path update
ref.updateChildren(updatedUserData, new Firebase.CompletionListener() {
   @Override
   public void onComplete(FirebaseError firebaseError, Firebase firebase) {
       if (firebaseError != null) {
           System.out.println("Error updating data: " + firebaseError.getMessage());
       }
   }
});
like image 174
Diego Venâncio Avatar answered Oct 23 '22 04:10

Diego Venâncio