How do I 'filter in' firestore data satisfying 'contains' condition?

Viewed 251

I just want to retrieve data according to node "City". Have a look to this image

Query query = fireStore.collection("Requests").whereEqualTo("City",Noida);

this query work when City node has the exact value ("Noida in this case") but I want to retrieve all data where "City" containing require data

for example: when City = Noida this case is working. What I want to do is

when City= Noida sec-32 and If I type Noida it still searches Noida sec-32

2 Answers

I don't think so you can implement this directly. But I can suggest you a way to do. You can add another field to the document like "sector" in which you can store the suburb of the city.

For eg. you can have city = "noida" and sector = "sector 32".

Like this you can query for city and then get the sector too.

There is no query in Firestore that queries substrings as you want.

But there is a workaround for small datasets,which consists in to query all the data and save in a variable ( In your case, getting all the cities name ) and use contains() method like this:

Query query = fireStore.collection("Requests");
String str1 = document.getString("City");
String str2 = "Noida";
boolean b = str1.toLowerCase().contains(str2.toLowerCase());

And if you print the value of b, if it matches it will return true, if not false. But the above examples works well enough only for small datasets, as it's not efficient for big datasets. In this case, as the official documentation recommends, you can enable full text search of your Cloud Firestore data, using a third-party search service like Algolia.

Related