Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase database - Query by list of ids

I have recently started switching my app from Parse to Firebase. Everything is going great so far, but I have not been able to find a Firebase equivalent method to Parse's whereContainedIn(String key, Collection values).

This was a very useful method that allowed me to pass in an array of ids and it would return all of the rows that matched that id. So far with Firebase, I have it returning all all of the rows in the database then looping through them to see if that row's id is contained in my array of ids. The other way is to query for each id individually, which doesn't work well with Firebase's asynchronous behavior. This is what I am doing now for the first approach:

List<String> userIds = new ArrayList<>();
userIds.add("2");
userIds.add("32");
userIds.add("12545");
userIds.add("187");

DatabaseReference firebaseRef = FirebaseDatabase.getInstance().getReference();
Query queryRef = firebaseRef.child("videos");

queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        List<Video> usersVideos = new ArrayList<Video>();

        for (DataSnapshot videoSnapshot : dataSnapshot.getChildren()) {
            Video video = videoSnapshot.getValue(Video.class);

            if (userIds.contains(video.userId)) {
                usersVideos.add(video);
            }
        }

        // usersVideos is now populated with the videos for the users

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.d(TAG, "CANCELLED");
    }
});

Neither of these methods seem reasonable since my table will contain hundreds of thousands of records.

Any help would be greatly appreciated!

like image 571
Mark Avatar asked Aug 08 '16 16:08

Mark


1 Answers

Make another reference that can be looked up by userId and have it return all videoIds that this user has. From there you can query the videos. That means each time you save you will need to save in two spots. Sort of a pain, but it is what Firebase recommends.

So your reference will look more like:

videos -
       | - <videoId> - 
             | - <video stuffs>
             | - userId
videosByUser -
       | - <userId> -
                    | 0 - <videoIdA>
                    | 1 - <videoIdB>
       | - <userId2> -
                    | 0 - <videoIdA>   
like image 159
Chad Bingham Avatar answered Sep 23 '22 03:09

Chad Bingham