Ngugi Kariuki
Ngugi Kariuki

Reputation: 184

Firebase multiple queries in android

I have this database:

Firebase db

The candidates collection contains several categories such as president and secretary. It also has totalVotes for each candidate. I would like to query:

  1. Results by category eg President or Secretary
  2. The candidate with highest 'totalVotes' per category, i.e, the President with the highest votes, and the secretary with highest votes.

Here is my code that is not working:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
        DatabaseReference candidatesRef = rootRef.child("candidates");
        Query specific = candidatesRef.orderByChild("category").equalTo("President");

        specific.orderByChild("totalVotes").limitToFirst(1);

        specific.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot){
                for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                    String firstname = childSnapshot.child("firstname").getValue(String.class);
                    String lastname = childSnapshot.child("lastname").getValue(String.class);
                    Long votes = childSnapshot.child("totalVotes").getValue(Long.class);
                    pres.setText(firstname + " " + lastname+" - "+votes+" Votes");
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException(); // don't swallow errors
            }
        });

How can I achieve this? Thanks

Upvotes: 0

Views: 207

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 139019

Unfortunately, there is no OR clause in Firebase. So you cannot filter the candidates on the category property based on multiple values.

There is a solution that might work but only if those values are in a range. In your case, you can get all candidates matching President or Secretary with:

ref.child("candidates")
   .orderByChild("category")
   .startAt("President")
   .endAt("Secretary")

The issue here is that it will also match candidates for other categories whose category is between President and Secretary if it exists. Besides that, you can not limit the query to 1 or 2 because you'll never know which candidate will have the highest number of votes. It might be a president, as well as a secretary.

So, there is no way in the Firebase Realtime Database to pass multiple values into a query. You need to perform separate queries for that and merge the result on the client.

If you consider at some point in time to try using Cloud Firestore, you can find there Query's whereIn(String field, List values) method that can help you solve this issue.

Upvotes: 1

Related Questions