Is it okay to filter firebase data using conditions? Will it affect the speed and accuracy of Firebase realtime database?

Viewed 34

Example:

final String campus = "BISU Calape";

private ValueEventListener valueEventListener = new ValueEventListener() {       
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        
        facultyList.clear();

        for(DataSnapshot dataSnapshot : snapshot.getChildren()){
            Faculty faculty = dataSnapshot.getValue(Faculty.class);
            faculty.setKey(dataSnapshot.getKey());
            if(faculty.getCampus().equals(campus) && faculty.getMemStatus.equals("Approved")){
                facultyList.add(faculty);
            }
        }

        if(facultyList.size() > 0){
            tv_noresult.setVisibility(View.INVISIBLE);
        }else{
            tv_noresult.setVisibility(View.VISIBLE);
        }

        adapter.notifyDataSetChanged();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        Toast.makeText(FacultyActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
    }
};

This code is working so far, but what if this code will have to fetch/filter millions of records?

1 Answers

The Firebase Realtime Database doesn't support queries on multiple properties. It supports only queries on a single child property. There is however a workaround in which you can create a new field in the database that can hold both values:

Firebase-root
   |
   ---- faculties
         |
         --- $campusId
                |
                --- campus: "BISU Main Campus"
                |
                --- status: "Approved"
                |
                --- campus_status: "BISU Main Campus_Approved"

So as you see, the campus_status field combines the values that you want to filter on.

So now, the following query will work:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference facultiesRef = db.child("faculties");
Query queryByCampusAndStatus = facultiesRef.orderByChild("campus_status").equalTo("BISU Main Campus_Approved");

Unlike the Realtime database, Cloud Firestore allows compound queries. This means that you can use multiple whereEqualTo() calls. So a query like the one below it will work perfectly fine:

facultiesRef.whereEqualTo("campus", "BISU Main Campus").whereEqualTo("status", "Approved");
Related