3

I am working on a system where users can subscribe to places and places can see these users in their CMS. But now I want to create statistics for the places.

Some of these statistics are:

  • How many males/female have subscribed to the place.
  • Age range of the users in my place.

How would these statistics work in Firebase? I could create a function and listen to the placeUsers node when something gets added or deleted. But the tricky part is that I need statistics per place.

I can't do it client-side because a place could potentially get millions of users.

Down here I pasted (a small fragment of) my current database setup.

{
    "users": {
        "<user-push-key>": {
            "name": "",
            "birthdate": 2138349423489,
            "gender": "male"
        }
    },
    "placeUsers": {
        "<place-push-key>": {
            "<user-push-key-1>": true,
            "<user-push-key-2>": true,
            "<user-push-key-3>": true
        }
    },
    "places": {
        "<place-push-key>": {
            "name": "",
            "location": ""
        }
    }
}
AL.
  • 36,815
  • 10
  • 142
  • 281
Stan van Heumen
  • 2,236
  • 2
  • 11
  • 20

1 Answers1

2

Unlike most traditional SQL databases, Firebase's Realtime Database is not well suited for ad-hoc aggregation queries. You will have to know up front what stats you want to track and update them as the data streams into/through your system.

Doing this client-side is certainly possible, but indeed not ideal. This is a perfect use-case for using the just-released Cloud Functions for Firebase. It falls closest to the use-case of sanitizing incoming messages:

data sanitization architecture

A good, simple example of an aggregation function is this child counter.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Certainly a good solution, but wouldn't you need to update all the placeStatistics when the users changes his birthdate? You wouldn't know his previous birthdate and you still need to update all the placeStatistics where the user is subscribed to. – Stan van Heumen Mar 15 '17 at 14:18
  • You can cater for a change in existing value, since your function gets both the current and the previous value. Other use-cases might require a different approach. – Frank van Puffelen Mar 15 '17 at 14:29