How to reduce query time in Firebase RTDB?

Viewed 93

I have a database in Firebase RTDB and usually I need to query today's and yesterday's records within one of the nodes and add them, which is about 60.

This query is very fast (less than a second) when the node is small or when the list of objects is cached, however as the node has grown (more than 10,000 objects), I see the query time slow down. it lengthens and longer (15 or 20 seconds) even though there are only 60 items to fetch, so I think I'm doing something wrong.

The way I am doing the query is as follows:

  Stream<List<SalidaAlimentoModel>> cargarSalidaAlimentoStream(String idEmpresa, int yesterday, int today) {

    final List<SalidaAlimentoModel> salidaAlimentoVacia = []; 

    Query resp = db.child('PATH').child('salidaAlimento')
                .orderByChild('fecha').startAt(yesterday).endAt(today);

    final publicarStream = resp.onValue.map((event) {
      if(event.snapshot.value != null) {
        final salMap = Map<String,dynamic>.from(event.snapshot.value as dynamic);
        final salList = salMap.entries.map((e) {
          SalidaAlimentoModel salimTemp = SalidaAlimentoModel();
          salimTemp = SalidaAlimentoModel.fromJson(Map<String,dynamic>.from(e.value));
          salimTemp.idSalidaAlimento = e.key;
          return salimTemp;
        }).toList();
        return salList;
      } else {
        return salidaAlimentoVacia;
      }
    });

  return publicarStream;

}

Within the Firebase rules I included an indexOn to ensure faster queries:

"salidaAlimento": {
  ".indexOn": ["fecha", "nombreRefAlimento", "nombreRefEstanque"],
},

Each of the objects (salidaAlimentoModel) occupies less than 1K and has a structure like the following:

{
  "-Mxy9ud7t40KtKYHj2eu" : {
    "cantidad" : 30,
    "comentarios" : "",
    "destino" : "-Mxy5l-i58WpoPk62e6l",
    "email" : "example@dbx.com",
    "fecha" : 1647089265202,
    "idAlimento" : "ALIMENTO1",
    "loteAlimento" : "Control Central",
    "loteEstanque" : "L1001",
    "mortalidad" : 2,
    "nombreAlimento" : "Alimento 1",
    "nombreRefAlimento" : "A1",
    "nombreRefEstanque" : "L1"
  },
  //---- More than 10,000 ----
}

How can I reduce the waiting time in Firebase RTDB when the node becomes big or huge?

ATTACHMENT

When I execute a firebase database:profile on console, the results are as follows:

Read Speed Read Speed salidaAlimento

Unlisten Speed Unlisten Speed salidaAlimento

Download bytes enter image description here

Unindexed Queries None

0 Answers
Related