0

How would I do a call to Firebase with multiple "WHERE" conditions?

this is my db:

users: {
   324234: {
      username: "admin"
      ...
   }
}

tracks: {
   12: {
      title: "Sample song"
      creatorId: 324234
      played: 24
      ...
   }
}

What I'm trying to do is in pseudo-sql:

SELECT FIRST 10 WHERE 'title' == searchQuery SORTED BY 'played'

I also want to be able to add: WHERE 'creatorId' == 324234 to the query.

I have gotten the search to work like this:

query = getTracksRef()
         .orderByChild("title")
         .startAt(query)
         .endAt(query + "\uf8ff")
         .limitToFirst(10);

And the sort to kinda work by sorting the items after I've gotten them from Firebase.

However because you can't have mutliple "orderBy" calls I simply don't know how to continue implementing the other conditions.

Grimbox
  • 203
  • 2
  • 7
  • Firebase Database queries can only order/filter on a single property. In many cases it is possible to combine the values you want to filter on into a single (synthetic) property. In your case that could be `"title_played": "Sample song_24"`. For another example of this and more approaches, see my answer here: http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase – Frank van Puffelen Dec 24 '17 at 01:59
  • @FrankvanPuffelen so in my example with 3 conditions (search query, order by played, creatorId == xxxx) i have to make another field title_played_creatorID? – Grimbox Dec 24 '17 at 20:57
  • @FrankvanPuffelen your solution will only work if the song has the same title? If I have two songs `"Sample song_9"` and `"Samx song_99"` and the query is `"Sam"` the orderby will order it accordingly to the title and not the played attribute – Grimbox Dec 24 '17 at 21:59
  • Correct: there can be only one partial/relative match, the others must be complete matches. There is no workaround for that limitation. – Frank van Puffelen Dec 25 '17 at 02:18
  • @FrankvanPuffelen so there is no solution that you know of with a serverless application? – Grimbox Dec 25 '17 at 14:19
  • The limits of the database are the same, no matter of you call it from a client SDK or from Cloud Functions. – Frank van Puffelen Dec 25 '17 at 15:10

0 Answers0