I am looking to add a simple search field, would like to use something like
collectionRef.where(\'name\', \'contains\', \'searchTerm\')
I tried
While Firebase does not explicitly support searching for a term within a string,
Firebase does (now) support the following which will solve for your case and many others:
As of August 2018 they support array-contains
query. See: https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html
You can now set all of your key terms into an array as a field then query for all documents that have an array that contains 'X'. You can use logical AND to make further comparisons for additional queries. (This is because firebase does not currently natively support compound queries for multiple array-contains queries so 'AND' sorting queries will have to be done on client end)
Using arrays in this style will allow them to be optimized for concurrent writes which is nice! Haven't tested that it supports batch requests (docs don't say) but I'd wager it does since its an official solution.
collection("collectionPath").
where("searchTermsArray", "array-contains", "term").get()
There's no such operator, allowed ones are ==
, <
, <=
, >
, >=
.
You can filter by prefixes only, for example for everything that starts between bar
and foo
you can use
collectionRef.where('name', '>=', 'bar').where('name', '<=', 'foo')
You can use external service like Algolia or ElasticSearch for that.
Late answer but for anyone who's still looking for an answer, Let's say we have a collection of users and in each document of the collection we have a "username" field, so if want to find a document where the username starts with "al" we can do something like
FirebaseFirestore.getInstance().collection("users").whereGreaterThanOrEqualTo("username", "al")
I agree with @Kuba's answer, But still, it needs to add a small change to work perfectly for search by prefix. here what worked for me
For searching records starting with name queryText
collectionRef.where('name', '>=', queryText).where('name', '<=', queryText+ '\uf8ff')
.
The character \uf8ff
used in the query is a very high code point in the Unicode range (it is a Private Usage Area [PUA] code). Because it is after most regular characters in Unicode, the query matches all values that start with queryText
.
I actually think the best solution to do this within Firestore is to put all substrings in an array, and just do an array_contains query. This allows you to do substring matching. A bit overkill to store all substrings but if your search terms are short it's very very reasonable.
We can use the back-tick to print out the value of a string. This should work:
where('name', '==', `${searchTerm}`)