Hitanshu Gogoi
Hitanshu Gogoi

Reputation: 987

Can I filter Multiple Fields in a Firestore search?

I use Firestore database in my app.
Now, is it possible to search for a particular word in multiple fields?

For example: Imagine a word like "cheesecake". Now, I have 100 documents in collection and each document has 10 different fields.
Can I filter for the word on all of the fields, so that it returns any document that contains the word "cheesecake" in any of the fields, in Flutter?

Upvotes: 5

Views: 16118

Answers (2)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

As creativecreatorormaybenot explained, there is no straightforward solution for your requirement. Filtering in the client side may be very time and money consuming, depending on the size of your database.

There is another possibility, which would be to enable full text search on Cloud Firestore documents by using an Algolia hosted search service. There is an official Cloud Function sample that shows how to set this up: https://github.com/firebase/functions-samples/tree/Node-8/fulltext-search-firestore

Upvotes: 1

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126694

No, you cannot do this.
Looking at the Firebase Firestore Documentation page about queries, you will find out about the following:

Cloud Firestore does not support the following types of queries:

This does not directly apply to your specific use case, but the reasoning for why your request will not work is similar: There is no index that allows you to sort according to multiple different fields.
You could e.g. create indexes that sort each of the fields, but only query them individually. To understand why certain queries are not supported, you can check out this in depth explanatory video from the Firebase team.

Concluding, this means that you will need to do the filtering client side.

Workaround Concept in Flutter

final QuerySnapshot querySnapshot = 
  await Firestore.instance.collection('cakes').getDocuments();
final List<DocumentSnapshot> documents = 
  querySnapshot.documents.where((snapshot) => snapshot.data.containsValue('cheesecake'));
// now the [documents] object will only contain documents, which have "cheesecake" as any of their fields

Upvotes: 6

Related Questions