Firestore Relevant Search

Firestore Relevant Search

5 min read

After I created my Full-Text Search in adv-firestore-functions, I thought to myself, there has got to be a better way! That is when I thought up Relevant Search. In Firestore you can search for a document just by the name in an array of hashes. For example: ```typescript const term = 'search query'; db.collection('some collection').orderBy('_terms/${term}'); ``` I can set that term to equal a number in Firestore, and sort by that number. Let's say there are 5 cases of the word document in a document. I can store that information in an array _terms like so: ``` collection --> _terms --> {document: 5, horse: 7} ``` By searching for document, and sorting descending, I can get an accurate proportion in order of the word document in a collection. To use it, simply put this in your Firestore function: ```typescript await relevantIndex(change, context, { fields: ['content', 'summary'] }); ``` It will handle all deletes, changes, etc. You will see the index in the _search collection. Make sure to enable writing in your Firestore Rules. That was not far enough. I also wondered if there were a way to get some sort of misspelling options, aka, Fuzzy Search. While you can't use Levenshtein Distance in Firestore due to your search options, you can use a front-end algorithm like soundex or metaphone. So, I created a way to add in those options, and included the English version of soundex in my package. ```typescript import { soundex } from 'adv-firestore-functions'; ... await relevantIndex(change, context, { fields: ['content', 'summary'], filterFunc: soundex }); ``` And just like that, you have the relevant index with soundex! Don't forget to install the package! ``` npm i adv-firestore-functions@latest ``` To actually use the search, you can write your own frontend, or you can use my callable function. Put this in your own callable function: ```typescript return await relevantSearch({ query: q.query, col: 'posts', }); ``` It will return an id and a relevance score like so: ```typescript { id: 23929, relevance: 23 }, { id: 2382, relevance: 14 } ``` You can write your own version on the frontend, preferably using observables, but this speed is not too bad as long as the microservice is warmed up. This is by far the best all-around search!
search
index
cloudfunction