Question:
I am querying Firebase from an Android app. The queries are as follows.
Consultation 1
reference.orderByChild("started").equalTo(true).addValueEventListener(new ValueEventListener() {...}
This query returns 5 results, but the consumption is 1.5 MB. It's like it returns all records. What can be happening?
I have done another test, with the following query, that data consumption does not occur:
Consultation 2
reference.limitToLast(5).addValueEventListener(new ValueEventListener() {...}
It also returns 5 records, but in this case it consumes only 10 KB .
How could I perform the first query without this excessive data consumption?
The consulted database has about 1500 records.
The database structure is this:
Game:
-KW_-cgwIPt5E8lzguds:
nivel1: array
nivel2: array
nivel3: array
nivel4: array
jugador1: String
jugador1Pts: int
jugador2: String
jugador2Pts: int
jugador1End: boolean
jugador2End: boolean
started: boolean
completed: boolean
-KW_-cgwIPt5E8lztyd5:
nivel1: array
....
And the full code is:
reference.orderByChild("started").equalTo(true)..addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
gameOnList.clear();
for (DataSnapshot gamesSnapshot : dataSnapshot.getChildren()){
Game game = gamesSnapshot.getValue(Game.class);
if(game.isStarted()) gameOnList.add(game);
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Answer:
The startAt(),endAt() and equalTo() operators have to traverse the entire array to filter it, in your case 1500 records. These operators have to be accompanied by an index in this node, thus facilitating the search.
{
"rules": {
"tuNodo": {
".indexOn": ".tuValor"
}
}
}
This would greatly reduce data consumption and execution time. If you want more information on how to index the data, take a look at this page . If it is still high, we would have to look at the option to denormalize the data. All the best!