Erik Sombroek
Erik Sombroek

Reputation: 165

Firebase, how to sort on key within date range

I have set up my data in my firebase realtime database as follows:

Key{ Creation date, Popularity, Rating, Author}

Would it be possible to retrieve the answers to the following questions:

  1. what where the top 50 games last month in terms of popularity?
  2. what where the lowest ranked games this week?
  3. what is the highest rated game today?

Answering one would answer the other one probably, but just to be sure I put them all.

Upvotes: 0

Views: 538

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

All of these require that you consider multiple properties. And since the Firebase Realtime Database can only order/filter over a single property, you can't perform these without modifying the data model. For a good primer, read my answer here: Query based on multiple where clauses in Firebase

In this case, you'd need three extra properties for each node:

  1. a property combining the month and popularity, for your first query. For example: "month_popularity": "201812_125" (if the popularity is 125).
  2. a property combining the month and rating, for your second query. For example: "week_rating": "2018w51_4".
  3. a property combining the day and rating, for your third query. For example: "day_rating": "20181225_4".

With these properties, you can then order on the interval you want, and filter the values for the range you want. For example to get the top 50 games for this month:

ref.orderByChild("month_popularity").startAt("201812_").endAt("201812~")

Where the ~ is just a character after _ in ASCII, ensuring that we stop returning results after the ones from this month.

Upvotes: 2

Related Questions