1

I have following Firebase Realtime Database structure.

enter image description here

I want to search a game with inviteCode = 271429. There are multiple categories, so I don't have a way to know if this particular invite code will fall under Maths.

I tried using .orderByChild() but that doesn't work on child of child. It works only if I know that I need to look in Maths.

I tried to look for a way if I could only get keys of 'games' and then I could loop in those keys looking for the code. I ended up finding shallow but it seems it is available for REST only. I am trying to implement this in Flutter.

I don't want to download the complete data and then search because the data size can be large.

What is the best possible solution to query such a database structure? Should I improve the database structure? Keep in mind the need to limit the number of calls to database to avoid excessive data calls because I believe Firebase charges based on it.

halfer
  • 19,824
  • 17
  • 99
  • 186
Saad Bashir
  • 4,341
  • 8
  • 30
  • 60

1 Answers1

2

Firebase Realtime Database queries work on a flat list of nodes. The key/value you are ordering/filtering on must be at a fixed path directly under each direct child node of the location you search.

The simplest solution here seems to be to add an additional data structure that maps the inviteCode values back to their category (and possibly other data about them). This is sometime referred to as a inverted index, and is quite common in NoSQL databases.

So you'd have:

invoteCodesLookup: {
  "271429": {
    category: "Maths",
    ...
  }
}

You can keep this and the original data structure in sync with multi-path updates and security rules.

For more on this, see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807