Home > Enterprise >  how to get users from firestore database with Like query
how to get users from firestore database with Like query

Time:03-21

this function work fine with equal string but i need to search a substring: if i write "h" and the string is "hello" i need to return that

async getUsers(searchUser) {
            
            return firestore().collection('Users').where(searchUser).where('firstName', '==', searchUser)
            .limit(20).get().then(snapshot => {
                snapshot.docs.forEach(doc => {
                    const usersData = { ...doc.data(), id: doc.id };
                    return usersData
                });
            })
        }

CodePudding user response:

I can give you answer! In that case, you must use a dedicated third-party search service. These services provide advanced indexing and search capabilities far beyond what any simple database query can offer. Please use "Algolia" and at that time your code according to your expectations must be like this.

const client = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
const index = client.initIndex('firstName');
index.search(searchUser, {
  attributesToRetrieve: ['firstname', 'lastname'/*, .. etc the fields you need*/],
  hitsPerPage: 20 /* the page Size */,
}).then(({ hits }) => {
  console.log(hits); // the results you want
});

Just try it. Helpful for you? If it's successful, I would be happy. If you have a question please contact "[email protected]". I will help you. Thanks.

CodePudding user response:

When you register a new user to your app you can store their username/firstname in firestore as an array that includes the possible ways you would search for a user (look at the attached image). You can do that by splitting the name string.

search options array in user doc in firestore

then you can query the users collection by searching in that array using arrayContains like this:

await usersCollection
        .where('searchOptions', arrayContains: searchText)
        .get()
        .then((value) =>
            value.docs.map((doc) => User.fromSnapShot(doc)).toList());

If you need more capabilities than that you might need to use a 3rd party service. but this solution should be sufficient for your case.

CodePudding user response:

Didn't you do yet? You can get 'install algoliasearch guide' at -https://www.algolia.com/doc/api-client/getting-started/install/javascript/?client=javascript -https://www.algolia.com/doc/guides/building-search-ui/installation/js/

  • Related