Lazy loading to the firing base?

I am trying to use a firebase database and I have checked the recommended way to model many or one to many relationships.

Let's say I have this relationship between mail and user: User has many messages.

This is my approach to model design:

class User{

List<String> postIds;

...
}

class Post{

String userId;

....
}

      

This is according to the firebase documentation here .

I like the design instead of embedding user generated messages under user collection like mongodb style, this design is flat; so later, if we only want to get users in the system, we also don't have to pull messages under the users.

But I doubt this design, even embedding IDs inside messages can be a problem later on; Imagine I have 100 users with 1000 posts each. If I want to show a list of users, I have to pull 100 users, which means I need to pull 100,000 posts.

Is there any lazy loading concept on firebase? those. when I get a custom object, the postIds shouldn't be loaded automatically; it should be downloaded on demand.

+3


source to share


2 answers


Firebase does not currently have a "lazy loading" or "load on demand" construct. All data under the location is read and transmitted on access. The only thing you can do is select User

and UserInfo

for two different branches so that you can apply to users individually, not by dragging unnecessary data.

class User {
  String id;
  String name;
  String gender etc.
}

class UserInfo {
  List<String> postIds;
  Other info maintained per user
}

      



This way, you can read users without pulling out additional information.

+2


source


An important rule of thumb in Firebase is to flatten the data as much as possible. You can take a look at this post, Structure Your Firebase Data Correctly for a Complex Application , for a better understanding.

Since there is no way in Firebase database to load just one property of each node, the only way to achieve this is to use a new node that contains all these ids. So if you want an efficient way to check if an ID exists or to count all users, only download a list of IDs. For good measure, you have to specify this list of ids in the database exactly.

To get all these ids, you can use this code:



DatabaseReference postRef = FirebaseDatabase.getInstance().getReference().child("Post");

postRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            String uId = ds.getKey();
            Log.d("TAG", uId);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
    throw databaseError.toException(); // don't ignore errors
    }
});

      

Hope it helps.

0


source







All Articles