Search code examples
javaandroidfirebasefirebase-realtime-database

Get just records count of a realtime database without retrieving all dates from database


UPDATED

My current code to get records count:

commentRef.child(poi.Id).addListenerForSingleValueEvent(new ValueEventListener() {
    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        commentList.clear();
        setProgressDialog();
        if (isAdded()) {
            counterValue = (int) snapshot.getChildrenCount();
            setCounter(counterValue);
        }
    } 

This returns me the record count.

If will modify with

public void onDataChange(@NonNull DataSnapshot snapshot) {
    commentList.clear();
    setProgressDialog();
    if (isAdded()) {
        counterValue = (int) snapshot.getChildrenCount();
        setCounter(counterValue);
        for (DataSnapshot comment_key : snapshot.getChildren()) {
            String comentariu = comment_key.child("text").getValue(String.class);
        }
    }
}

from same snapshot will get information text field. And in same manner can get all fields data.

I concluded that although I want to receive only the number of records, the snapshot contains information about all the records in the database (so all the records are sent to me by the server) and only in my device is the total number of records obtained with snapshot.getChildrenCount().

What I want is to reduce the information I download from the server to the minimum necessary to save money. Downloading all information will artificially increase costs.


Solution

  • The Firebase Realtime Database always returns the raw information as it exists at the node you load. It doesn't support any kind of aggregation operation, such as counting the nodes.

    This means that the only way to get the count of the nodes in the database (through the SDK) without downloading the data, is to actually store that count in the database and update it whenever you create or delete a node. That's for example what this simple Cloud Functions sample does: Tracking the number of elements in a list.

    Expanding your database to support a specific use-case is quite common in NoSQL databases. To learn more about this and other best practices, I recommend reading NoSQL data modeling and watching Firebase for SQL developers.

    Also see: