0

Hello I have an app that has about 5000 users/month. I app looking to scale my app and would like to restructure my users in the database. My app allows users to perform searches on other users and I do not want to query the single collection I have for all the users every time. I was thinking of splitting the users collection into sub collections of each letter of the alphabet and users would be assigned to the associated sub collection bases on the first letter of their username. However this presents one problem which is getting the current users data. I also use firestore authentication to log in users and after the authentication I retrieve a uid. But I cannot know the current users sub collection because I don't have the first letter of their username. Maybe there is a way to modify firestores uid creation to input a pointer letter at the front of the uid. If anyone knows a better way to structure the database I would appreciate the help. Thanks

getting a user looks something like this. (the code below is reduced)

guard let letter = uid.first.map(String.init) else { return }
Firestore.firestore().collection("users").document(letter.uppercased()).collection("users")
            .document(uid)
            .getDocument { snapshot, _ in
                guard let snapshot = snapshot else { return }
                guard let user = try? snapshot.data(as: User.self) else { return }
                completion(user)
            }
ahmed
  • 341
  • 2
  • 9
  • *I do not want to query the single collection I have for all the users every time* -- why? *users would be assigned to the associated sub collection bases on the first letter of their username* -- why? Both seem like ways to complicate your life, not simplify it. – anothermh Apr 05 '23 at 17:51
  • @anothermh firestore charges for large collection queries. If I have 100k users down the line and all in one collection. Then I would have 100k users that are queried per request. And every user can submit dozens of requests per day. This can add up and increase my document reads by a lot. – ahmed Apr 05 '23 at 17:56
  • @anothermh Additionally it is much faster to query a collection that is smaller than a huge collection – ahmed Apr 05 '23 at 17:57
  • *much faster* -- that's just [plain wrong](https://stackoverflow.com/a/60229124/3784008). And what does your proposed solution do to resolve that? Are you intending for users to be able to query only people whose names start with the same letter? Besides, [you're charged only for the results returned by the query](https://stackoverflow.com/a/50140120/3784008), not by the number of documents queried. – anothermh Apr 05 '23 at 18:00

0 Answers0