Firebase: How to structure data for the most share

2019-08-01 20:47发布

问题:

Let's assume there is a blog and you would like to list the most liked or shared posts for today, the last 7 days and the last 30 days.

The solution for today is rather easy:

-mostSharedPostsForToday
   -2018-10-08
       -$postId
           -numberOfShares

Then the query would observe mostSharedPostsForToday/2018-10-08 for today's most shared posts ordered by child numberOfShares.

But how to structure the data for the most shared posts in the past n days?

One solution I can think of is to write a cloud function that populates the node mostSharedPostsForThePastNDays on a daily basis. But it seems cumbersome to me. Isn't there a more efficient way?

Edit: As pointed out in the comments of the 1st answer pagination should be supported to save traffic.

回答1:

I recomand you to use another approach. In stead of using the date as your node, remove that node and add a TIMESTAMP for each post like this:

-mostSharedPostsForToday
   -$postId
       - TIMESTAMP: 2018-10-08
       - numberOfShares: 10

To know how many shared you have in a single day, you need to use the following code:

rootRef.child("mostSharedPostsForToday").child(postId).orderByChild("TIMESTAMP").equalsTo("2018-10-08");

And if you want an interval please use the following code:

rootRef.child("mostSharedPostsForToday").child(postId).orderByChild("TIMESTAMP").startAt("2018-10-08").endAt("2018-10-15");

Hope it helps.