0

I've got this code:

func filteredUsers(_ query: String) -> [User] {


    let lowercasedQuery = query.lowercased()
    return users.filter({ $0.fullname.lowercased().contains(lowercasedQuery) || $0.username.contains(lowercasedQuery) })
}

I am getting users from my database that match the searched text (inputted by the user).

The problem is that, since my initial user base has grown, it calls all the users registered and that becomes a very long list.

When I fetch my users

     func fetchUsers() {
        guard let currentUid = AuthViewModel.shared.userSession?.uid else { return }

       
//        COLLECTION_USERS.limit(to: 10).getDocuments { snapshot, _ in
        COLLECTION_USERS.getDocuments { snapshot, _ in
            guard let documents = snapshot?.documents else { return }
            self.users = documents.compactMap({ try? $0.data(as: User.self) }).filter({ $0.id != currentUid })
        }
    }

And use the commented line, it only searches the database for the first 10 users in the list, not for all users. Is there any way where I still search the entire database but only retrieve 10 values that match the query, not only searching for the first 10 users?

Any help would be appreciated, thanks!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

1

You'll want to use a Firestore query, instead of performing the search in your application code. With a Firestore query, the filtering is performed by the database, instead of in your application code.

The simplest way to search is:

let dbQuery = COLLECTION_USERS
    .whereField("fullname", isGreaterThanOrEqualTo: query)
    .whereField("fullname", isLessThanOrEqualTo: query+"\u{F7FF}")

This query searches for documents where the fullname starts with the given value.

A few things to note:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807