Sylvester Agyapong
Sylvester Agyapong

Reputation: 35

How to search through multiple fields in my firestore database through flutter

I'm trying to build a search functionality where a text entered in my search field is search through two fields in my Firestore(profileName and username). For example, if a user has the profileName 'Sylvester Appiah' and username 'keeett'. Then when either the username or profileName is searched it should return the same user. I'm not sure if I can do profileName or username inside the .where() method. Any help is appreciated!

controlSearch(String searchWord){
 Future<QuerySnapshot>pUsers=usersReference 
  .where("profileName",isGreaterThanOrEqualTo:searchWord)          
  .getDocuments();
   setState(() {
      futureSearchResult = pUsers;

    });
  }

Upvotes: 2

Views: 2419

Answers (2)

Faris Albagdali
Faris Albagdali

Reputation: 1

I added a new field as a list field to each document under the name search keywords and put the fields that I wanted to search.

example:

await FirebaseFirestore.instance.collection('your collection').doc().set({
'name' : 'Faris',
'age' : 25,
'country' : 'Iraq',
'search keywords' : [
  'Faris',
  25,
  'Iraq',
],

});

and when I want to search I will use the search keywords field key.

Stream<QuerySnapshot> get searchFilteredData {
return FirebaseFirestore.instance
    .collection('your collection')
    .where('search keywords',  arrayContains: searchFilter)
    .snapshots()
    .handleError((error) => print(error.toString()));

}

then, you can use StreamBuilder to search and get data.

One of the drawbacks of this method is that you have to type the exact value in order to fetch the required data, it is not enough to write part of the value.

I learned this way from this YouTube video

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 600126

You can't pass multiple conditions to where(). Instead you can call where() multiple times, chaining them together into the query you need:

usersReference
  .where("profileName",isGreaterThanOrEqualTo: searchWord)
  .where("username",isEqualTo: "QeustionableCoder")
  .getDocuments();

Note that you may need to define an index for such multi-field queries. If you're missing an index, the SDK will log an error message about that. Look for the URL in that error message, as it is the fastest way to define an index on the correct fields.

Upvotes: 5

Related Questions