Home > OS >  How to read data from Firebase Realtime Database conditionally
How to read data from Firebase Realtime Database conditionally

Time:02-08

Assume that I have the following structure in my Firebase Realtime database:

- users
  - g123
    - john
      - age: 30
      - active: 1
    - mike
      - age: 20
      - active: 0
    - johanna
      - age: 30
      - active: 1
  - g456
    - jake
      - age: 20
      - active: 1
    - maria
      - age: 20
      - active: 0
  - g789
    - elli
      - age: 20
      - active: 0
    - joe
      - age: 20
      - active: 0

I need to get the list of child:s where there is at least 1 user with active set to 1.

So, in the example above, there are 2 active users in g123 and 1 active user in g456. And there is no active user in g789.

How do I build a query to Firebase Realtime database (preferably with Python) that will return g123 and g456?

CodePudding user response:

Firebase Realtime Database queries work on a flat list of nodes, and the value to order/filter on must be at a fixed path under each direct child node. So the sort of query you want, is not possible on this data structure.

A common workaround is to store the activeCount under each direct child node, and update that upon each write.

- users
  - g123
    activeCount: 3
    - john
      - age: 30
      - active: 1
    - mike
      - age: 20
      - active: 0
    - johanna
      - age: 30
      - active: 1
  - g456
    activeCount: 0
    - jake
      - age: 20
      - active: 1
    - maria
      - age: 20
      - active: 0
  - g789
    activeCount: 3
    - elli
      - age: 20
      - active: 0
    - joe
      - age: 20
      - active: 0

You can then order/filter on this activeCount.

Also see:

  •  Tags:  
  • Related