1

I'm trying to do a "where" query in Flutter-Firebase to filter by name (if the object name is "Una casa roja" and the user writes "casa", the object must be returned). I don't know who can I do the query. I only have this, but is not what I am looking for:

.where('nombre', isGreaterThanOrEqualTo: nombre, isLessThan: nombre + 'z')

Thanks!

deslarry
  • 31
  • 1
  • 6
  • Unfortunately there's not a **string contains** in Firestore queries when it comes to string fields. You'll have to pull down all the names and do it locally (i.e. looping through all results and then doing a "string contains" logic. Otherwise you'll have to do it on the server side using a Cloud Function or something. Hopefully your dataset is not too large so you can do it on the client side without much processing cost. See this answer https://stackoverflow.com/questions/51452823/it-is-possible-to-have-a-contains-search-query-in-firebase/51456002 – Roman Jaquez Mar 22 '22 at 13:52
  • If I had known that limitation of Firebase, I would never have chosen it in the first place. What a shame :( – Stefan Dec 18 '22 at 16:50

2 Answers2

3

Unfortunately, You can't do this. Firebase documentation says that you can't do it. I don't know why firebase doesn't support that. But to do that you can use third-party APIs such as Agolia or Elastic. For more information you can get it in their documentation in this link https://firebase.google.com/docs/firestore/solutions/search

0

Firestore doesn't support text-search by default. However, there are a few workarounds.

When you register a new user to your app you can store their username in firestore as an array that includes the possible ways you would search for a user (look at the attached image). enter image description here

You can do that by splitting the name string.

setSearchParameters(String name) {
        List<String> searchOptions = [];
        String temp = "";
        for (int i = 0; i < name.length; i++) {
          temp = temp + name[i];
          searchOptions.add(temp);
        }
        return searchOptions;
  }

Then you can query the users collection by searching in that array using arrayContains like this:

await usersCollection
        .where('searchOptions', arrayContains: searchText)
        .get()
        .then((value) =>
            value.docs.map((doc) => User.fromSnapShot(doc)).toList());

This solution works for simple cases but if you need advanced search capabilities then you'll have to use a 3rd party service such as Agolia.

amo
  • 123
  • 3