Flutter Profile Matching App - Cloud Firestore Data Modeling | How to Query to avoid unnecessary reads for already swiped UID´s - firebase

I tried my best with the search function and not really getting the results I´m searching for.
At the moment I try to replicate a functionality for swiping profiles on a card stack. The profiles are loaded over a Firebase Firestore backend. The problem is, due to the geoFireStore query, I get with every load within a specific radius a whole bunch of documents and I would like to reduce the read amount directly in the query.
So what I'm trying to achieve is, that when I swiped a profile once (left or right) I never want to read it in the query again. In addition, to save reads, I don't want to do this client sided, it should be done in the query directly.
Firestore JSON structure at the moment:
Users (collection)
UIDs [documents]
name
active
match {map}
If the match map doesn't contain the own UID (if exist is null) then read in query, else when own UID exist in other user profile under the map match (boolean: true or false for liked or disliked) then don't show as query result.
My stream is built this way:
return geo
.collection(
collectionRef:
friendrCollection.where("active", isEqualTo: true).where("match.$uid", isNull: true))
.within(
center: geoFirePoint,
radius: suchRadius,
field: 'position',
strictMode: false)
.map(_friendrsGPSListFromSnapshot);
}
I am working on this for 3 weeks now and not getting the results I want :D
-Should I stay with firestore or better the real-time-database?
-How do I need to structure the data to get a "except" query working?
Right now it is like:
Collection: Users --> Documents: UIDs --> Match{ownUID}
Thanks in advance
Andreas :)

I still not managed to find a proper solution to reduce the number of unnecessary profile reads inside the firestore query.
Has anyone an idea to handle this part?
The only way I found was to lookup existing matches on the client side (extra firestore collection), but that means that I always have to load the whole bundle of profiles and throwing them away afterward :(
Thank you!
Andreas

Related

How to listen for changes(or get stream) from nested sub collections?

I am building a private chat feature for my app. I have chosen Firestore as my back end and below is how chat threads and messages are structured.
privateChats - chatId1 - chatId1 - messageId1, messageId2,...
collection - document - collection - documents
here is the screenshot
What I am trying to achieve is to get snapshots of every chat threads(chatId1, chatId2,...) with their corresponding message(last document/message was sent) and display like below - refer Chat screen
I have tried something like that
databaseRef.collection('privateChats').where('chatId', whereIn: chatList).snapshots();
However streams which are returned from above snapshots only listen for changes on fields where createdAt field exists.
Which gives me an only option to get individual snapshot for each chat threads like that
databaseRef.collection('privateChats').doc('chatId1).collection('chatId1).snapshots();
databaseRef.collection('privateChats').doc('chatId2).collection('chatId2).snapshots(); and somehow combine these snapshots into single stream (I don't know how)
So my question is - is there a way to get snapshots of each chat threads with just a single query when given list of chat ids? If not, what could be the solution? Should I come up with different cloud firestore structure?
Thanks
what i think you can do is create a doc for each chatRoom ..like say
databaseRef.collection('privateChats').doc('chatId1+chatId2')
then both users id1 and id2 can only access the document
I solved my problem using rxdart MergeStream function as emir adejuwon suggested

how to wrap my head around a FireStore query

I am new in Flutter - Firestore
I am learning flutter with firebase and creating a sample dating app
I have a list of users that I get in a stream and display it using List view
Firestore.instance.collection('users').snapshots()
I have learnt to filter this like so
.where((user) => user.age < settings.agemax && user.age > settings.agemin))
and all this works.
I also have a subcollection called shortlist (list of users that current user has shortlisted) that I get using,
Firestore.instance.collection('users').document(uid).collection('shortlist').snapshots()
Now I am trying to redefine my first query GetUsers with filters based on following
How do I exclude shortlisted users that I am fetching in a stream from all users stream
Similarly would also need to filter out "matched users" and "Blocked / declined" users as well !
I believe my question is how do I query Users Collection and exclude records with uid's that contained in a Shortlist subcollection. I am planning to use the same logic for matches and blocked !? am I on the right track ?
also ... do I need to refetch all records when a users shortlists/matches/blocks someone, as the stream would change or is there a way to remove that one record from the listview without rebuilding, may be I should separate this question in two.
If I understand correctly you are looking for the (just introduced) not-in operator, so I recommend also checking out this blog post.
I expect that this operator hasn't landed in the Flutter libraries yet, as that may take some time. I recommend checking the upcoming releases to see when it lands, or checking/filing an issue on the repo.
Until then, there's no way to exclude results from a query, so you will have to exclude the items from the stream of results in your application code.

Firebase database check if element exists in a ListField in Flutter

I have a real-time database on firebase which consists of ListFields. Among these fields, one field, participants is a list of strings and two usernames. I want to make a query to firebase database such that it will return the documents in which a particular username is present in the participants list.
The structure of my document is as follows :
I want to make a query such that Firebase returns all the documents in which the participants list consists aniruddh. I am using Flutter with the flutterfire plugins.
Your current data structure makes it easy to find the participants for a conversation. It does however not make it easy to find the conversations for a user.
One alternative data structure that makes this easier is to store the participants in this format:
imgUrls: {},
participants: {
"aniruddh": true,
"trubluvin": true
}
Now you can technically query for the the conversations of a user with something like:
db.child("conversations").orderByChild("participants/aniruddh").equalTo(true)
But this won't scale very well, as you'll need to define an index for each user.
The proper solution is to add a second data structure, known as an inverted index, that allows the look up of conversations for a user. In your case that could look like this:
userConversations: {
"aniruddh": {
"-LxzV5LzP9TH7L6BvV7": true
},
"trubluvin": {
"-LxzV5LzP9TH7L6BvV7": true
}
}
Now you can look up the conversations that a user is part of with a simple read operation. You could expand this data structure to contain more information on each conversation, such as the information you want to display in your list view.
Also see my answer heres:
Firebase query if child of child contains a value (for more explanation on why the queries won't work in your current structure, and why they won't scale in the first structure in my answer).
Best way to manage Chat channels in Firebase (for an alternative way of naming the chat rooms).

Firestore Search - LIKE

I want to search the "displayName" in documents nested within a collection, or more specifically the data is as follows:
users -> $idstring -> displayName
Ive come up with the following using AngularFire but its still not quite working for me.. I need to check displayName against the first 3 chars of val (user entered) and bring back results that start with that, I need a kind of LIKE search operation to occur, is this possible with firestore.. so far its just returning almost everything in my users collection
this.itemsCollection = this.aft.collection<iUser>('users', ref => ref.orderBy("displayName").startAt(val))
As mentioned on the Cloud Firestore Documentation:
Cloud Firestore doesn't support native indexing or search for text
fields in documents. Additionally, downloading an entire collection to
search for fields client-side isn't practical.
And to enable full text search of your data, you'd need to use a third-party search service like Algolia or ElasticSearch.
The documentation actually provides a guide on how to integrate Algolia with Firebase.

Firebase - Structuring Data For Efficient Indexing

I've read almost everywhere about structuring one's Firebase Database for efficient querying, but I am still a little confused between two alternatives that I have.
For example, let's say I want to get all of a user's "maxBenchPressSessions" from the past 7 days or so.
I'm stuck between picking between these two structures:
In the first array, I use the user's id as an attribute to index on whether true or false. In the second, I use userId as the attribute NAME whose value would be the user's id.
Is one faster than the other, or would they be indexed a relatively same manner? I kind of new to database design, so I want to make sure that I'm following correct practices.
PROGRESS
I have come up with a solution that will both flatten my database AND allow me to add a ListenerForSingleValueEvent using orderBy ONLY once, but only when I want to check if a user has a session saved for a specific day.
I can have each maxBenchPressSession object have a key in the format of userId_dateString. However, if I want to get all the user's sessions from the last 7 days, I don't know how to do it in one query.
Any ideas?
I recommend to watch the video. It is told about the structuring of the data very well.
References to the playlist on the firebase 3
Firebase 3.0: Data Modelling
Firebase 3.0: Node Client
As I understand the principle firebase to use it effectively. Should be as small as possible to query the data and it does not matter how many requests.
But you will approach such a request. We'll have to add another field to the database "negativeDate".
This field allows you to get the last seven entries. Here's a video -
https://www.youtube.com/watch?v=nMR_JPfL4qg&feature=youtu.be&t=4m36s
.limitToLast(7) - 7 entries
.orderByChild('negativeDate') - sort by date
Example of a request:
const ref = firebase.database().ref('maxBenchPressSession');
ref.orderByChild('negativeDate').limitToLast(7).on('value', function(snap){ })
Then add the user, and it puts all of its sessions.
const ref = firebase.database().ref('maxBenchPressSession/' + userId);
ref.orderByChild('negativeDate').limitToLast(7).on('value', function(snap){ })

Resources