Can I filter Multiple Fields in a Firestore search?

走远了吗. 提交于 2020-12-04 04:59:59

问题


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?


回答1:


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:

  • Queries with range filters on different fields, as described in the previous section.

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



回答2:


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



来源:https://stackoverflow.com/questions/52277456/can-i-filter-multiple-fields-in-a-firestore-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!