0

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 :

Document Structure

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.

  • Not sure it is possible in firebase. You will have to get all the participants and then loop over them in flutter. – Tinus Jackson Jan 07 '20 at 10:28
  • Would you recommend using a different structure where I have two separate fields as `participant_0` and `participant_1` such that I can run an OR query to fetch the documents in which the query username is either `participant_0` or `participant_1`? – Aniruddh Chandratre Jan 07 '20 at 10:31
  • Yes i would do something like that, not sure if its frowned upon. Example `Query query = query.where('participant_0 ', isEqualTo: participant_0 );` Check if query is empty then do the second check for participant_1 – Tinus Jackson Jan 07 '20 at 10:36

1 Answers1

0

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807