Search Lessons, Code Snippets, and Videos
search by algolia
X
#native_cta# #native_desc# Sponsored by #native_company#

Angular Full Text Search With Algolia Backend - Part 2

Episode 28 written by Jeff Delaney
full courses and content on fireship.io

In the first Algolia Full Text Search lesson, I showed you how to quickly build a full text search interface with Algolia InstantSearch and Angular. In the second part, we will use Firebase Cloud Functions to create and maintain our own index with the realtime database.

Create a new Index in Algolia

The first step is to create a new index from the Algolia dashboard. Make a note of the name, which is books in this example.

Database Design

In this example, we have a collection of books, and every book has an author and title.

-|books
-|bookId
author: string
title: string

Preparing the NodeJS Environment

The cloud function needs the algoliasearch package and environment variables for your Algolia API credentials. Make sure to use the admin API key.

cd functions
npm install algoliasearch --save
firebase functions:config:set algolia.adminkey="YOUR_KEY" algolia.appid="YOUR_APP_ID"

Cloud Function - Indexing a Document

A document must be indexed before it can be searched. This function is invoked when a book is created or updated in the database. If the book does not have any data, it is deleted from the Algolia index.

const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp();

const algoliasearch = require('algoliasearch');
const firebaseConfig = JSON.parse(process.env.FIREBASE_CONFIG);
const algolia = algoliasearch(firebaseConfig.algolia.appid, firebaseConfig.algolia.adminkey);


exports.updateIndex = functions.database.ref('/books/{bookId}').onWrite(event => {

const index = algolia.initIndex('books');

const bookId = event.params.bookId
const data = event.after.val()

if (!data) {
return index.deleteObject(bookId, (err) => {
if (err) throw err
console.log('Book Removed from Algolia Index', bookId)
})

}

data['objectID'] = bookId

return index.saveObject(data, (err, content) => {
if (err) throw err
console.log('Book Updated in Algolia Index', data.objectID)
})

});

Pretty simple! Algolia has many other indexing options available may be helpful if you need to index multiple documents in a single pass, or if you want to update individual properties in the index.

Update the Angular App

Back in Angular, we just need to change the indexName in the options object that is passed to InstantSearch. This object can be updated in the environment file.

export const environment = {
production: false,

algolia: {
appId: 'APP_ID',
apiKey: 'SEARCH_ONLY_KEY',
indexName: 'books',
urlSync: false
}
};

That’s it for Algolia with Firebase Cloud Functions.