How To Structure Data For Auto-Complete Search In Firebase

I am creating a social network app and I need to find an appropriate way to structure my Cloud Firestore database in order to store users. At the client side, the app should present a search bar to find and add other users. Ideally, as you type a character onto this search bar, users whose names begin with the inputted character should be displayed and updated as you input more characters onto the search bar in realtime (i.e., implementing auto-complete). Therefore, I am trying to find the optimal way to store users onto Firestore that facilitates this querying process.

I thought about storing each user's complete information in a separate document within a user collection (i.e. having one document for each user). If I implemented like this, I could use inbuilt Firestore queries via Google Cloud Functions. However, every time a query was made then inbuilt Firestore queries would scan all the user documents (i.e., a document for each user would be expensive and inefficient if number of users got large).

To be more economical and efficient, I could have a separate collection (e.g. pointer collection), in which each user name and ID to the complete user document (in the user collection) are grouped in documents organized in alphabetical order. For example, I could have one document for all user names starting with "a", where the fields of this document would indicate the names and document IDs to the user collection (similarly for all other letters). Once, any of these documents for a given letter would get full (reach the limit Google decided), I could simply add a sub-collection to it to store additional user names and IDs, for example, by organising the sub-collections based on the first two characters of the users' name (e.g. "aa", "ab" , "ac" etc.).

As a result, I could use these documents in the pointer collection to quickly display users' name starting with given characters onto the search bar, and once a specific user is selected from it, I could use the document ID to retrieve the full user document in the user collection (so, I wouldn't need to scan through all user documents).

I would like to ask whether this type of structuring data makes sense or not for the presented problem? And is there a better way to do it?

Thanks in advance!



keystroke search is not supported by firestore, you would need to find an alternate 3rd party like Algolia or App Engine Search

Both have a generous free layer and you don't even need to arrange your collections in a complex way, take a look at this article to get you started and also this specific android api.

For the amount of user you mentioned you have, the free tier should fit your case without problems.