How to use Firebase for statistics?

2020-03-25 06:00发布

问题:

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": ""
        }
    }
}

回答1:

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:

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