Firestore Full-text Search

Firestore Full-text Search

4 min read

**Update: 2/17/21** - There are now more search options to choose from! See here! In my adv-firestore-functions npm package, you can now index documents to be searchable like so: ```typescript import { eventExists, fullTextIndex } from 'adv-firestore-functions'; exports.myFunction = functions.firestore .document('posts/{docId}') .onWrite(async (change: any, context: any): Promise => { // don't run if repeated function if (await eventExists(context)) { return null; } // index the posts const searchable = ['content', 'title']; searchable.forEach(async (field: string) => { await fullTextIndex(change, context, field); }) return null; }); ``` Use my fullTextIndex function. Simply import it, and add the fields you want to index like in the example. This function will index the content and title fields of the posts documents. Every time a new document is added, an index is added. If you delete the document, the indexes are deleted. If you modify the document, they are modified. This function is the key to indexing any document. It takes care of batch limits, parses out text from html, and will neatly store the indexes in the _search collection. ``` npm i adv-firestore-functions ``` There will be only as many searchable documents as there are words in the field, duplicate groups of 6 (you can change this to smaller if you wish), and the documents have one field, and a foreign key to the posts document. And on the front end, you use something like this for searching: ```typescript let id = firebase.firestore.FieldPath.documentId(); const col = _search/COLLECTION_NAME/COLLECTION_FIELD; db.collection(col).orderBy(id).startAt(term).endAt(term + '~').limit(5); ``` See the npm package or the github repository for more information. Here is a [gist example](https://gist.github.com/jdgamble555/257df098104a2f754af8d88821a4cdf8) of how to use this in angular by separating each word... Happy Searching!
cloudfunction
index
search