Let’s get started with Algolia…

Yudhajit Adhikary
10 min readMay 1, 2022

--

Hi Guys, today we will be discussing about a wonderful search and recommendation service, Algolia. Algolia empowers Builders with the Search and Recommendation services they need to build world-class experiences.

So we will divide your discussion into seven parts:

1. What is Algolia ?

2. How to push data in Algolia using API ?

3. How to implement Searching in Algolia ?

4. How to implement Filtering in Algolia ?

5. How to implement Sorting in Algolia ?

6. Demo

7. Conclusion

So let Begin…..

1. What is Algolia ?

Algolia is a hosted search engine that offers full-text, numerical, and faceted search. Algolia’s powerful API lets us quickly and seamlessly implement search within our websites and mobile applications. Algolia also have analytical capable of delivering real-time results from the first keystroke.

2. How to push data in Algolia using API ?

Algolia provides several ways to push data in their portal dashboard . The data can be pushed manually or using api. We will see in our demo how it is done through api. Algolia used to store data in a collection called index. We can also replicate an index , these replicated index are mostly used for sorting. Algolia is having a built-in function replaceAllObjects() which used to push all the data from json or from any other api to algolia. We will be seeing how this function works in our demo.

index.replaceAllObjects(array objects)

index.replaceAllObjects(array objects, {
// All the following parameters are optional
safe: bool,
// + any requestOptions
})

3. How to implement Searching in Algolia ?

In order to implement search in Algolia, we have to define searchable attributes in our Algolia portal , like whenever user type something in the search bar , the search result should come according to searchable attributes value . We can also give preference if we want to add multiple searchable attributes in the portal. There are two ways to define searchable attributes in Algolia , one is by added searchable attributes manually in the portal, or using setSettings() function to do the same through API.

index.setSettings({ 'customRanking': ['desc(followers)'] }, {
forwardToReplicas: true
}).then(() => {
// done
});

4. How to implement Filtering in Algolia ?

In Algolia Filtering is handled by facets. In order to allow Algolia to perform facetting we have to define Attributes for faceting on Algolia portal. We can also use setSettings() function just like this to define our Attributes for faceting.

index.setSettings({
attributesForFaceting: ['genre', 'author']
});

5. How to implement Sorting in Algolia ?

So for implementing sorting like sort by price , sort by name in Algolia, we have to create replica of the parent index, like let’s say we are having an index for product called productsIndices , we want to perform sorting by price and by name, So what we can do we can create two replica index from productIndices one for sort by price, and one for sort by name. And we can give custom ranking from Ranking and Sorting tab in Configuration from our dashboard, we will be seeing those later, Just we have to define which parameter let’s say price or name should come in which order (ascending or descending order). So what we have to do we will fetch data from that particular index , like when there is no sorting options selected we will take data from productIndices, if now user clicks on sort by price we will fetch data from that particular replica of productIndices which is specified to handle the price sorting.

Now enough theory , to make the things clearer we will be creating a small application that performs pushing, searching , sorting , filtering using Algolia.

So let’s get started …

6. Demo

Now it’s demo time , let’s start coding together , so open your vsts we will be first create our very basic react boilerplate. So we have to run

npx create-react-app <Project name>

once it’s done we will be having a simple react boilerplate , now we have to do cd <tab> enter then run npm run start to run our application to localhost 3000.

So in order to start with algolia we have to install algolia , so to do that run :

npm i algolia

So now our basic boilerplate is up and running , now let see the folder structure of our code base:

Mostly this codebase is same as react boilerplate, only change we have done is we have added adapter folder which is having the adapter files. algolia.adapter.js is having functions to fetch data from algolia. algoliaIndexManager.js is having algolia class object where we have defined few variables and methods . algoliaClient.js is defining the algolia client we will be using to fetch the data , where as pushingdata.js is having function to push data to algolia. Let’s first do the setup for Algolia in our algolia portal:

So we will first go to this url:

Here we have to login , we can take the free trial version for learning purpose .

When we are done with login there will be a default space already created for use.We can use the same .

So Now if we scroll down we will see there in Settings in left side bottom. If we click on that we will get an option API Keys where we will get all the Api key required to make our application working.

We need two Api Keys Admin API Key and Application Id. Now let’s put those in our codebase and start creating our client, AlgoliaClient.js

In AlgoliaClient.js , we have defined a function getWriteClient() where we are declaring our Algolia client, then we are returning the client. Finally we are export getWriteClient that will return the algolia client.

Now let see the datapushing.js the file which is having scripts to push data to algolia from our data.js.

Now let’s see the datapushing.js :

In datapushing.js, we are pushing data to our algolia dashboard, in getFieldObject() we are creating key , value pair that we are pushing in algolia. push() is pushing data into algolia, in this push function we are checking if data.length >0 ,we are declaring variable pushedData that will store the pushed data. Then we are importing replaceAll, setSettings and createReplica methods from IndexManager.js which defines the algolia class object. Then we are mapping through the data and for each node we are pushing node in pushedData array, we are calling the replaceAll function with pushedData as argument. Similarly we are calling setSettings function with an array having ‘name’ as argument, finally we are calling createReplica function with an array having values ‘Demo-Index-desc(name)’ and ‘Demo-Index-desc(price)’. We will be looking into those functions in algoliaIndexManager.js.

In algoliaIndexManager.js , we have defining our algolia class object ,we defining variables and methods like name, index, replaceAll(), setSettings() and createReplica (). Inside our IndexManger class we are setting name as the name that is coming as argument , then we are setting the index by calling getWriteClient() with this.name, this name will be the name of the index we want to create. We are defining replaceAll(), this function will actually store the records in our Index ,this.index is having the current index so there we are calling algolia’s built-in function replaceAllObjects with data and configuration settings coming as argument of the method.

In setSettings() we are actually setting the searchable attributes of our index using algolia’s built-in setSettings function.

Similarly createReplica() is used to create replica of our Index (these replicas are used for Sorting). So we having created two replicas from our Index (Demo-Index) ,‘Demo-Index-desc(name)’ and ‘Demo-Index-desc(price)’.

Please note to push data into algolia we have to go to the respective path ,where the file is present and run node datapushing.js from our terminal, Once you run that and everything went well , you will see records coming on Algolia portal dashboard.

Now if you can see there are two replicas of our Demo-Index index, Demo-Index-desc(name) and Demo-Index-desc(price). Demo-Index-desc(name) will be having the data sorted name wise , where as Demo-Index-desc(price) will be having the data sorted price wise. So to do that we have to go to the Configuration → Ranking and Sorting , and will have to add custom ranking like this :

Now let’s see App.js:

In App.js we are defining our dom structure of our application , we will be keeping your application simple. Our application will be having a product listing page having all products listed . We can search a product by it’s name, we can also filter products based on the category of the products ,also we can sort products by price and by name. So we have imported getAlgoliaResults() and getAlgoliaSearchResults() from algolia.adapter.js , these two functions are actually fetching data from Algolia. Inside our App function we are defining three states data ,loading , inputQuery. data represents the product data we will be rendering in the listing page ,loading represents the boolean data which indicates when the page is loading or fetching data from algolia and inputQuery represents the query we are searching on our search box . Inside useEffect() we can calling loadData() function , where we fetching the initial data from algolia that we will be rendering on first load. So first we setting loading as true , then we are fetching data from algolia by calling getAlgoliaResults() function, once we get the data we using setData to set the state data ,then we are setting loading as false. Now let go down to the return section to see the dom structure ,we have added a title , then we have placed an input field which will be our search box. So whenever user is typing something in the input field onChange of it we are calling handleInputChange() function. In handleInputChange() we are setting the value of inputQuery with the query. On clicking the Search button we are calling searchResult(). In searchResult() we are getting the data according to query (inputQuery) we are passing in search box. Then we are having few filtering options Like Shirt, Sneaker, Bag, Watch, Kefiah and All (For all products) ,we have kept buttons for each product category to perform filtering, onClick of those buttons we are calling SelectProduct1() by passing the particular category name as an argument. In SelectProduct1() we are doing faceting for filtration , So we are passing two parameters to perform the faceting, one is facets array that contains the parameters which will be considered as facets and facetFilters another array which contains the facet category according to which filtering should happen ,for example facetFilters:[facetCollection:watch] means show those products which are having watch in the array facetCollection. We have also implemented the sorting functionality where we are sorting the data according to product’s name and price. handleSort() function is handling the sorting functionality , inside handleSort() function we are calling getAlgoliaResults function to get the data accordingly to the name we are passing as argument , like if the name is price, we will be fetching data from that specific Index that is containing product data sorted according to their price .

So lastly we are just mapping through our data and rendering our product cards having product image, name and price. The functions for fetching data from algolia is defined in algolia.adapter.js let ‘s have a look on that .

So in algolia.adapter.js we are having two functions, getAlgoliaResults() and getAlgoliaSearchResults(). getAlgoliaResults() is used to fetch data according to the request-object (facetting) and name (sorting) passed as argument, so we are first determining the name of the index we will be using according to the sorting option user have selected (sorting) ,then we are initiating our Index with that name , and calling algolia built-in search function with the request-body coming as an argument (facetting) to get filtered data. getAlgoliaSearchResults() is used to handle the search functionality of our application , so we are just calling the same built-in search function with the query string instead of keeping the string empty. So we have done the whole code base walk-though , Now let’s see the output:

7. Conclusion

Ohh Okay that’s was a lengthy one , So in this article we have discussed the basic concepts of how to perform searching , sorting and filtering functionality using Algolia. But I will suggest please go through the documentation of algolia first before getting started with it ,it is very nice, helpful and descriptive :

I am attaching the GitHub code link as a reference of this article:

HAPPY CODING….:)

--

--

Yudhajit Adhikary

Web developer by profession,Photographer,Blog Writer,Singer,Pianist,Seeker of Solution