Firebase multiple queries in android

馋奶兔 提交于 2020-04-18 05:45:44

问题


I have this database:

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


回答1:


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.



来源:https://stackoverflow.com/questions/61107058/firebase-multiple-queries-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!