Filter by search keyword in cloud firestore query
This is a problem that you always have to tackle if your app or website has a search box. We want to get all the records that contain a certain keyword that the user enters.
Unfortunately 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.
There are some third party search providers like Algolia or ElasticSearch but their services are paid.
I have researched it quite a bit as of now and found three solutions which all are given in this Discussion at StackOverflow.
The answer marked as the solution to the question can me modified to work as the best solution but then we need to compute all the combinations in UPPER CASE, lower case and Type Case as well as any other that the user might type. The author itself doesn’t recommend that solution anymore.
The other two working solutions both have demerit of not being case sensitive so you must format your data in cloud firestore in a consistent way such that you can first convert the input string in that format and then query.
Another demerit is that the search string must start with the first letter as it can’t look for a substring within a string. The substring must be at the start of the result String.
Ex — if you want to search for String ‘India’ then you have to start typing Capital ‘I’ then n d … you can’t type ‘dia’ and expect India in the results.
Anyways both the solutions are intuitive and you can definitely try them to see if they work for you or not.
Solution 1:
Use the following query
Firestore.instance
.collection('your-collection')
.orderBy('your-document')
.startAt([searchkey])
.endAt([searchkey + '\uf8ff']
Solution 2:
Firestore.instance
.collection('Col-Name')
.where('fieldName', isGreaterThanOrEqualTo: searchKey)
.where('fieldName', isLessThan: searchKey +’z’)
Both the solutions work the same you can try whichever works for you.
If you like my work consider supporting me
Thanks:)