Skip to content Skip to sidebar Skip to footer

Leave Only Nn Newest Entries And Delete All The Rest

I have the following structure. Each user has his own data. ---+ root_child | +---+ Gy7FXRbRjDfAKWu7a95NgiGIZUk1 (Firebase User Id) | | +---+ KlNlb71qtQ

Solution 1:

I would probably use the sort and filter functions.

First, I would grab the children count with a single value listener: https://stackoverflow.com/a/43607203/7949696 , Or in the case of a cloud function I would count the children from the snap on the write trigger.

Then, if childCount > 100, I would OrderByChild() on your timestamp and then filter by LimitToLast(childCount - 100)

If I were you, I would use cloud functions to achieve this and set a function on write to root_child/${uid}/


Edit: Source code link from comments: https://github.com/firebase/functions-samples/tree/master/limit-children

Cheers!


Edit 2: Looks like push() is chronologically sorted, so no need to OrderByChild

Solution 2:

Algorithm:

  1. AddListenerForSingleValueEvent is called only 1 time to get all the data and to delete all the old ones
  2. Then we call only addChildEventListener to get only new data

        databaseReference.orderByKey()
            .addListenerForSingleValueEvent(valueEventListener =
                    newValueEventListener() {
                        @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
                            longcount= dataSnapshot.getChildrenCount();
                            longdeleteFirst= count - Const.FB_MAX_CHILD;
                            longi=0;
    
                            Log.i(TAG, "DataSnapshot children count = " + String.valueOf(count));
                            for (DataSnapshot data : dataSnapshot.getChildren()) {
                                i++;
                                if (i <= deleteFirst) {
                                    // delete
                                    Log.i(TAG, "delete => " + data.getKey());
                                    data.getRef().removeValue();
                                } else {
                                    TrackDatatrackData= data.getValue(TrackData.class);
                                    Log.i(TAG, data.getKey() + " = " + trackData.toString());
                                }
                            }
                        }
    

Post a Comment for "Leave Only Nn Newest Entries And Delete All The Rest"