Back to Blog Home
← all posts

Seek, and Ye Shall Find: The Algolia Plugin

August 2, 2017 — by Jen Looper

This article is second in a series highlighting interesting NativeScript plugins built by our community. What plugins are you using? Which do you like most? Let us know in the comments.

ambassadors.csv

So, you have built an app that has a lot of interesting content, and you need it to be searchable. Look no further than the Algolia plugin, written by Arpit Srivastava. Algolia offers solid, easy-to-implement search capabilities for your web sites and mobile apps, and is a great addition to create intelligent searches for your content. Designed to closely mirror Algolia’s JavaScript library, the NativeScript plugin allows the app developer to incorporate intelligent search capabilities easily. Here’s how!


Step 1: Create an Algolia Account and an App

First, you need to create an account on Algolia.com and choose a plan. There is an excellent free Community plan for testing; you can always upgrade to a paid plan later. Once you have enrolled, you are presented with a dashboard and an API key. If you’re using a free plan, you should display the Algolia logo on your search page like so:

Simulator Screen Shot Jul 14, 2017, 12.24.30 PM

Once you have created your account, you need to expose your searchable data in Algolia. Create a new App, and get ready to dump data into it. Your data is stored as an index in the Indices tab in your dashboard. This index is a sort of bucket of data, and you can configure it in the dashboard to be sliced and diced many different ways.


Step 2: Upload your data to Algolia

Algolia recommends uploading your data into your Index via an API client. The way my recipe app, QuickNoms, works is that a user can enter a new recipe on the front end of the web site (http://www.quicknoms.com) and, after the content is approved in Firebase by setting the data’s ‘approved’ boolean to ‘true’, the recipe appears on both the web and mobile site instantly. Ideally, I would upload each new recipe to Algolia via an API call on the web, or use a Firebase function to do this for me. Firebase functions that touch external APIs, however, are only available on paid plans. So for the time being, to have some queryable data immediately, I used a node script built by Josh Dzielak to dump the data from my Firebase account to my Algolia dashboard. Now I can view my data, which I have imported in to the “recipes” Index.

Note, to simply test this service, you can upload data manually to Algolia via its dashboard, but this is not a good strategy for the long term.


Step 3: Install and Initialize the Algolia-NativeScript plugin

Now you need to take a look at the plugin documentation that we are going to use. As Arpit states in the ReadMe, this plugin mirrors the standard JavaScript implementation as designed by Algolia, so if you have integrated Algolia Search on the web, this won’t feel too different. 

In my NativeScript-Angular app, I first install the plugin: tns plugin add nativescript-algolia

Then, I initialize the plugin with my API key in my search component, using the app id that I have created in the Algolia dashboard and my API Key. Finally, I initialize my index named “recipes”, making it ready to be searched:

import {Algolia} from "nativescript-algolia";
var client = new Algolia('<app-id>', '<api-key>');
var index = client.initIndex("recipes");

Step 4: Prepare your Search Screens


In my search component’s html (recipe-search.component.html), I have created a layout with a search bar and a place for searched recipes to be displayed in the standard card format of this app:
  <StackLayout class="green">
    <SearchBar #SearchBar (submit)="search($event)"></SearchBar>
    <ScrollView height="87%">
        <WrapLayout horizontalAlignment="center">      
            <StackLayout style="margin-left: 10" class="card" width="45%" *ngFor="let recipe of recipes">
                <StackLayout horizontalAlignment="center" (tap)="goToRecipe(recipe.id)">
                    <Image [src]="recipe.Image"></Image>            
                    <Label class="name" horizontalAlignment="center" textWrap="true" [text]="recipe.Name"></Label>
                </StackLayout>
            </StackLayout>           
        </WrapLayout> 
    </ScrollView>
    
    <Image src="~/images/search-by-algolia.png" style="margin:5;width:200"></Image>
    
</StackLayout>
Once a search is submitted, the search term searches the prepared index. Any ‘hits’ in the resulting search are pushed into the this.recipes array, and displayed in the card interface:

search(e: any) {
        this.loader.show({ message: 'Finding recipes...' });
        //clear array
        this.recipes = [];
        this.term = "";
        if (e && e.object) {
            this.term = e.object.text;
            index.search(this.term, (results, errors) => {
                for (let id in results.hits) {
                    let result = (Object).assign({id: results.hits[id].objectID, Name: results.hits[id].Name, Image: results.hits[id].Image});
                        this.ngZone.run(() => {
                             this.recipes.push(result);
                        })                       
                      this.loader.hide();
                    }
                })           
            }
            else {
                alert("Sorry, no recipes found!");
                this.loader.hide();
            }
            
    }

search

Like standard Algolia searches, the plugin supports ‘smart’ search to tune the search’s behavior. You can add custom sorting such as by recipe type: show breakfast foods before snacks, for example. You can also configure the list of attributes you want to index by order of importance - for example, the name of the recipe could rank ahead of content in its ingredients and method:

index.setSettings({
  'searchableAttributes': [
    'Name',
    'Ingredients',
    'Method'
  ]
}, function(err, content) {
  console.log(content);
});

I strongly recommend using this beautiful plugin with its powerful search functionality in your mobile apps! What a great experience it can offer for a content-heavy app. Have you used this plugin recently? Let us know in the comments!