Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically create indexes for Cloud Firestore?

I have a Collection of Lists in which I store a bunch of documents. Each document contains a few details and a Collection of users. I store the users within the users Collection using the uid as a key and a boolean as a value. This means that only those users will be able to read that particular list. This is my database structure.

enter image description here In my code I use this query:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference listsRef = rootRef.collection("Lists");
Query query = listsRef.orderBy("date").whereEqualTo("users."+uid, true);

And I get the following error:

FAILED_PRECONDITION: The query requires an index. You can create it here: ...

If I go to the Console to create the required index, everything works fine. But is there a possibility to create the indexes automatically, because I cannot create manually an index for each user that joins my app. Is there a problem if I have a few sorting indexes for each user?

Is there another workaround?

Thanks in advance!

like image 881
Joan P. Avatar asked Dec 24 '17 13:12

Joan P.


1 Answers

Cloud Firestore automatically creates indexes on individual fields of your documents. Complex indexes that span multiple fields can (currently) only be created manually in the Firebase console.

If you find that you need to create indexes programmatically, you typically should consider augmenting your data structure to allow a reverse lookup. For example, in your scenario, I'd add a userLists collection where you keep the lists for each user.

like image 191
Frank van Puffelen Avatar answered Oct 05 '22 03:10

Frank van Puffelen