Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase query: exclude data where a specific field is null

I have a query that fetches data between 2 dates, using startAt (1 week ago) and endAt (now) on the last_visit fields.

Then I loop through the results to discard users who don’t have a profile picture.

Problem is around 20% of the users have a profile picture, so just to get 100 users with profile pictures, I have to query at least 500 people (I use limitToLast(500)).

Could I make this query more efficient, by somehow specifying something like in SQL: WHERE profile_picture IS NOT NULL?

If possible, I could also use only limitToLast(100) if it was possible to only take the users that do have a profile picture set.

Database looks like:

users: {
  {user_uid}: {
     profile_picture: null,
     last_visit: 123456789
  }
  {user_uid}: {
     profile_picture: 'example.com/pic.png',
     last_visit: 123456789
  }
}
like image 604
Dan P. Avatar asked Feb 06 '23 07:02

Dan P.


1 Answers

If you're trying to exclude items that don't have a property, you need to query for the broadest range of values possible.

A simple example would be:

ref.orderByChild('profile_picture').startAt('!').endAt('~')‌​

This will capture most keys that consist of ASCII characters, since ! is the first printable character (#33) and ~ is the last printable character (#126). Be careful with these, because they won't work when your keys consist of unicode characters.

like image 78
Frank van Puffelen Avatar answered Feb 13 '23 05:02

Frank van Puffelen