1. Home
  2. Blog
  3. Post
  4. Firestore Full Text Search

Total Posts: 7

Tags:

  • cloud function (6)
  • counter (1)
  • faq (1)
  • helper function (1)
  • index (4)
  • search (4)
  • timestamp (1)
  • trigger function (1)

Firestore Full-text Search

4 min read

Firestore Full-text Search

Finally there is a way to implement a full-text search without using Algolia or Elastic Search!

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:

import { eventExists, fullTextIndex } from 'adv-firestore-functions';

exports.myFunction = functions.firestore
    .document('posts/{docId}')
    .onWrite(async (change: any, context: any): Promise<any> => {
 
        // 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:

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 of how to use this in angular by separating each word...

Happy Searching!


cloud function
index
search