Issue
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.
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!
Solution
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.
Also note that not all queries need a unique index, as Firestore may be able to merge indexes (especially) for more complex queries. This can drastically reduce the number of unique indexes you need.
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.
Answered By - Frank van Puffelen
Answer Checked By - Candace Johnson (JavaFixing Volunteer)