Firebase - How to delete many entries at once?

2020-07-05 05:58发布

问题:

How do I delete all entries for the given push ID?

For example, let's say KoxoxwTqfb50E1Gvi9F push ID is in many locations of my database i.e. under many keys and I want to delete all entries for KoxoxwTqfb50E1Gvi9F at once as opposed to statically deleting all entries (since I know their locations).

In other words, is there a way to tell Firebase "delete all entries for KoxoxwTqfb50E1Gvi9F across the entire database"?

回答1:

In order to delete multiple entries from your database, you need to know all those locations (refernces). So with other words, in the way you add data, you should also delete it.

Assuming your database looks like this:

Firebase-root
   |
   --- Users
   |     |
   |     --- userUid1
   |     |      |
   |     |      --- //user1 data
   |     |
   |     --- userUid2
   |            |
   |            --- //user2 data
   |
   --- Groups
         |
         --- groupId1
         |      |
         |      --- //group1 data
         |      |
         |      --- Users
         |            |
         |            --- userUid1: true
         |            |
         |            --- userUid3: true
         |
         --- groupId2
                |
                --- //group2 data

I suggest you using the method below:

private static void deleteUser(String userId, String groupId) {
    Map<String, Object> map = new HashMap<>();
    map.put("/Users/" + userId + "/", null);
    map.put("/Groups/" + groupId + "/Users/" + userId + "/", new HashMap<>().put(userId, null));
    //other locations
    databaseReference.updateChildren(map);
}

This method atomically deletes all those entries. Using these paths, you can perform simultaneous updates to multiple locations in the JSON tree with a single call to deleteUser() method. Simultaneous deletes made this way are atomic: either all updates succeed or all updates fail.

Hope it helps.