简体   繁体   中英

Firebase query all users who are not friends with user - flutter

I'm trying to make social media app using flutter. one key feature with apps like this is looking for friends, and I would like to implement this in my app.

Here's a look in my Firestore Database: 在此处输入图像描述

We have a collection of "users" where we store their data and a subcollection "friends" where we store the userID of the added users: 在此处输入图像描述

Let's say user "4uuBry" is friends with user "5083CM", then "5083CM" should not be seen in a list of friend suggestion for "4uuBry".

So how do I query all users who are not friends with "4uuBry" and display them in a ListView?

EDIT Sep 18 2020

The Firebase release notes suggest there are now not-in and != queries. ( Proper documentation is now available.)

  • not-in finds documents where a specified field's value is not in a specified array.
  • != finds documents where a specified field's value does not equal the specified value.

Neither query operator will match documents where the specified field is not present. Be sure the see the documentation for the syntax for your language.

ORIGINAL ANSWER

Firestore doesn't provide inequality checks. According to the documentation :

The where() method takes three parameters: a field to filter on, a comparison operation, and a value. The comparison can be <, <=, ==, >, or >=.

Inequality operations don't scale like other operations that use an index . Firestore indexes are good for range queries. With this type of index, for an inequality query, the backend would still have to scan every document in the collection in order to come up with results, and that's extremely bad for performance when the number of documents grows large.

If you need to filter your results to remove particular items, you can still do that locally.

You also have the option of using multiple queries to exclude a distinct value. Something like this, if you want everything except 12. Query for value < 12, then query for value > 12, then merge the results in the client.

Example:

  QuerySnapshot querySnap = await FirebaseFirestore.instance
        .collection('chat')
        .where('participant', arrayContains: myEmployeId)
        .where('type', isEqualTo: '1') //you will change the query here
        .get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM