Search by Algolia
Building a performant search bar in Nuxt with Algolia & Storefront UI
engineering

Building a performant search bar in Nuxt with Algolia & Storefront UI

In today's highly competitive e-commerce landscape, providing customers with a seamless and efficient search experience can make all ...

Jakub Andrzejewski

Senior Developer and Dev Advocate at Vue Storefront

How to use AI to build your business
ai

How to use AI to build your business

The world of technology is constantly evolving with generative Artificial Intelligence (AI) currently leading the charge. We’re suddenly surrounded ...

Abhijit Mehta

Director of Product Management

Haystack EU 2023: Learnings and reflections from our team
ai

Haystack EU 2023: Learnings and reflections from our team

If you have built search experiences, you know creating a great search experience is a never-ending process: the data ...

Paul-Louis Nech

Senior ML Engineer

What is k-means clustering? An introduction
product

What is k-means clustering? An introduction

Just as with a school kid who’s left unsupervised when their teacher steps outside to deal with a distraction ...

Catherine Dee

Search and Discovery writer

Feature Spotlight: Synonyms
product

Feature Spotlight: Synonyms

Back in May 2014, we added support for synonyms inside Algolia. We took our time to really nail the details ...

Jaden Baptista

Technical Writer

Feature Spotlight: Query Rules
product

Feature Spotlight: Query Rules

You’re running an ecommerce site for an electronics retailer, and you’re seeing in your analytics that users keep ...

Jaden Baptista

Technical Writer

An introduction to transformer models in neural networks and machine learning
ai

An introduction to transformer models in neural networks and machine learning

What do OpenAI and DeepMind have in common? Give up? These innovative organizations both utilize technology known as transformer models ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

What’s the secret of online merchandise management? Giving store merchandisers the right tools
e-commerce

What’s the secret of online merchandise management? Giving store merchandisers the right tools

As a successful in-store boutique manager in 1994, you might have had your merchandisers adorn your street-facing storefront ...

Catherine Dee

Search and Discovery writer

New features and capabilities in Algolia InstantSearch
engineering

New features and capabilities in Algolia InstantSearch

At Algolia, our business is more than search and discovery, it’s the continuous improvement of site search. If you ...

Haroen Viaene

JavaScript Library Developer

Feature Spotlight: Analytics
product

Feature Spotlight: Analytics

Analytics brings math and data into the otherwise very subjective world of ecommerce. It helps companies quantify how well their ...

Jaden Baptista

Technical Writer

What is clustering?
ai

What is clustering?

Amid all the momentous developments in the generative AI data space, are you a data scientist struggling to make sense ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

What is a vector database?
product

What is a vector database?

Fashion ideas for guest aunt informal summer wedding Funny movie to get my bored high-schoolers off their addictive gaming ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Unlock the power of image-based recommendation with Algolia’s LookingSimilar
engineering

Unlock the power of image-based recommendation with Algolia’s LookingSimilar

Imagine you're visiting an online art gallery and a specific painting catches your eye. You'd like to find ...

Raed Chammam

Senior Software Engineer

Empowering Change: Algolia's Global Giving Days Impact Report
algolia

Empowering Change: Algolia's Global Giving Days Impact Report

At Algolia, our commitment to making a positive impact extends far beyond the digital landscape. We believe in the power ...

Amy Ciba

Senior Manager, People Success

Retail personalization: Give your ecommerce customers the tailored shopping experiences they expect and deserve
e-commerce

Retail personalization: Give your ecommerce customers the tailored shopping experiences they expect and deserve

In today’s post-pandemic-yet-still-super-competitive retail landscape, gaining, keeping, and converting ecommerce customers is no easy ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Algolia x eTail | A busy few days in Boston
algolia

Algolia x eTail | A busy few days in Boston

There are few atmospheres as unique as that of a conference exhibit hall: the air always filled with an indescribable ...

Marissa Wharton

Marketing Content Manager

What are vectors and how do they apply to machine learning?
ai

What are vectors and how do they apply to machine learning?

To consider the question of what vectors are, it helps to be a mathematician, or at least someone who’s ...

Catherine Dee

Search and Discovery writer

Why imports are important in JS
engineering

Why imports are important in JS

My first foray into programming was writing Python on a Raspberry Pi to flicker some LED lights — it wasn’t ...

Jaden Baptista

Technical Writer

Looking for something?

facebookfacebooklinkedinlinkedintwittertwittermailmail

A friend and I recently brainstormed how we could support our local bands while Covid continued to limit their opportunities to play live shows. We came up with an idea for a website where bands could sell limited-edition poster prints and t-shirts. The website would be designed to create a sense of community and urgency by promoting new items as they became available on social media, also known as ‘drops’, similar to what the fashion brands and the sneaker world have succeeded in doing. 

We chose Algolia as our main tool because it offers front-end libraries that make it easy to spin up an ecommerce site with a top-tier search and discovery experience for customers. We decided to  leverage the search capabilities and modularity of InstantSearch for React. Here’s a rough diagram of what we wanted to build:

The challenge of instant inventory updates

The goal of the project was to create a sense of urgency when new products get released. The technical challenge, therefore, was to display an up-to-the-second inventory to our users. Searching and retrieving information from Algolia indexes is lightning fast, providing as-you-type instant search results. On the other hand, updating the data on the back end can take a little more time. However, we discovered that if we were to update our index every time the inventory changed, it would have slowed down both the search results and the rendering times of some front-end components.

We’re going to look at how we were able to use and adapt InstantSearch to build an almost up-to-the-second search capability for an ecommerce website.

Using Algolia Widgets for InstantSearch

Algolia InstantSearch offers incredibly fast search results, and it allowed us to scan through designs quickly to create the desired sense of urgency. The Autocomplete functionality inside InstantSearch added discovery, as users see suggestions they might not have considered. 

I wanted to build the site in React because it offers good choices for ecommerce design and cross-platform compatibility. InstantSearch for React is a library of pre-built front-end React widgets that make getting started with a site layout a very quick process. The component diagram above maps well to a few of these widgets:

  • SearchBox and RefinementList are in the upper left in our mockup above
  • Autocomplete feeds the “Are you looking for…” suggestions in the upper right 
  • Hits is the list of search results on the left

If you don’t have an Algolia Index, create an account and app. We created a <SearchBox> component that contains the first three widgets (SearchBox, RefinementList, and Autocomplete), and a <Hits> component for the Hits widget, displaying our list of products. The <ProductDetail> component uses our own data and code, since it doesn’t come from the Algolia index.

We had a problem with this design, though, which is that it requires us to update and retrieve data from our Algolia index constantly. As we mentioned above, Algolia indexes are optimized for retrieval. Their engine prioritizes search, with fast indexing a close second. We didn’t want to flood the server with index updates which could slow down the search, the rendering of <Hits>, or limit the functionality in <SearchBox>, all of which depend on super-fast data retrieval with every keystroke. We came up with a solution – separate our inventory data updates from our search processing, so that we could update the inventory without touching our main index. 

We went back to our site mock-up, and found we could work around this problem by customizing the InstantSearch widgets

Create a Second Algolia Index for Inventory

The solution that lets us have both as-you-type instant search results and instant inventory is to have two separate Algolia indexes. If you don’t already have an Algolia Index, create an account and app.

One of the indexes is a typical product index. The JSON looks like this:

[
 {
  "objectID": 42,
  "title": "Return to Paranormal",
  "band": “Out In The Cold”,
  "designer": “Jamie Deer”,
  "introduction_date": “2021-09-23T18:25:43.511Z”,
  "sizes": [“adults”, “kids”, “pets”],
  "_tags": ["Seattle", "aliens", “punk”]
 }
]

This is just a simple record. Eventually, we will include more information in the index, such as links to the band and designer websites, image URLs, etc. 

The second index is simpler:

[
 {
   “objectID”: 42,
   “remaining_editions”: 18
 }
]

Now we can update the smaller inventory index without impacting the main index used for <Hits>.

Using two indexes also requires splitting up the UI into two separate components for each Hit result, but it’s a simple adjustment:

We moved the remaining_editions number out of the <Hits> component and into its own separate custom widget, which we rendered as a separate component, called <Inventory>. Both indexes, and both components, use the same objectID

It’s important to note that we’re not making <Inventory> a child of <Hits>, because we need to keep the rendering of these two components separate. That’s why the <SearchPage> component holds <SearchBox>, <Hits>, <Inventory>, and <ProductDetail> at the same level.

Using React Hooks to Keep Everything Available

As you might have noticed, we rely on three data sources:

  1. Algolia Index (on Algolia’s servers) – This index provides the data to populate the <Hits> and <SearchBox> components. The data in here is an extract from our back-office database (3), which gets updated regularly when product listings change.
  2. Algolia Inventory Index (on Algolia’s servers)  – This index provides the updated remaining_editions attribute displayed in the <Inventory> component. The remaining_editions attribute comes from our back-office database (3).
  3. Our back-office database (on our servers) – We maintain a detailed back-office database of products, which includes lengthier product descriptions and purchase data. We pull inventory changes from this database and update the <ProductDetail> component asynchronously, with the exception of remaining_editions, which is displayed to the <Inventory> component.

We have two goals in this application: one, to offer “instant” inventory numbers, and two, to keep as-you-type instant search results enabled at all times. Here’s how we accomplish both goals.

InstantSearch Never Slows Down

Keeping InstantSearch fully available is non-negotiable. Customers can understand a couple of seconds of delay in inventory, but they won’t tolerate slow or glitchy search functionality. Here’s how we structure this part:

  • We use a pretty standard implementation of InstantSearch, with one change that requires us to connect a custom component for Hits
  • In our <SearchPage> component, we use React state hooks and create a setter method for setObjectIDs that gets passed to the <Hits> component. 
  • As Hits render, we capture the objectIDs in an array with a handler method, then pass that back up to <SearchPage>
  • In terms of managing asynchronous API calls, this is our first priority, so the only thing the Hits widget is waiting for is the InstantSearch API. We could have managed this with a useEffect() hook in <Hits>, but Algolia provides a method in InstantSearch that achieves the same goal: onSearchStateChange

These steps get us the information we need from <Hits> without interrupting the UI or data flow of the as-you-type InstantSearch functionality – we just plug in to the middle with our connected component and use a built-in method to trigger updates.

Code for SearchBox.js:

import { InstantSearch } from 'react-instantsearch-dom';
import SearchBox from './SearchBox.js';
import CustomHits from './Hits.js';
import Inventory from './Inventory.js';
import ProductDetail from './ProductDetail.js';
 
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
 
function SearchPage() {
 const [objectIDs, setObjectIDs] = useState([]);
 const [selectedObject, setSelectedObject] = useState({
   objectID: null,
 });
 
 return (
   <React.Fragment>
     <InstantSearch
       indexName="product_index"
       searchClient={searchClient}
       searchState={{
         query: '',
       }}
       onSearchStateChange={searchState => {
         if (searchState) {
           setObjectIDs();
         }
       }}
     >
       <SearchBox />
       <CustomHits
         objectIDs={objectIDs}
         setObjectIDs={setObjectIDs}
         selectedObject={selectedObject}
         setSelectedObject={setSelectedObject}
       />
       <Inventory objectIDs={objectIDs} />
       <ProductDetail selectedObject={selectedObject} />
     </InstantSearch>
   </React.Fragment>
 );
}
 
export default SearchPage;

Code for Hits.js`:

import React from 'react';
import PropTypes from 'prop-types';
import { connectHits } from 'react-instantsearch-dom';
 
function Hits({ hits, objectIDs, setObjectIDs }) {
 const handleSearch = () => {
   hits.map(hit => objectIDs.push(hit.objectID));
   setObjectIDs(hits);
 };
 return (
   <ol>
     {handleSearch}
     {hits.map(hit => (
       <li key={hit.objectID}>{hit.name}</li>
     ))}
   </ol>
 );
}
 
Hits.propTypes = {
 hits: PropTypes.arrayOf(PropTypes.object),
 objectIDs: PropTypes.arrayOf(PropTypes.string),
 setObjectIDs: PropTypes.func,
};
 
const CustomHits = connectHits(Hits);
export default CustomHits;

“Instant” inventory updates are close to real-time

Now that we are set up to capture the objectIDs, we need to set up our inventory updates. There are three separate situations where we will be calling our inventory index: two for the <Inventory> component, and one within the <ProductDetail> component. 

In order to display up-to-the-minute inventory information, we need two data points: the array of objectIDs for the current results in <Hits>, and the most recent number from our inventory index. The objectIDs are now held in <SearchPage>, and update each time the searchState changes, so passing them down into <Inventory> is easy. To get the info from our inventory index, we use another built-in Algolia method: index.getObjects(). This lets us go directly to the objects we want without having to create another InstantSearch instance. 

Note that as of algoliasearch@4.0.0, the getObject() and getObjects() methods are not available in the lite build, which is the default import – you’ll just need to update the import statement.

Once we make the initial connection, setting up the second call to the inventory index is simple. We added a setInterval() function inside a useEffect() hook to call the inventory index every two seconds. That way, even if a user doesn’t update their search term, inventory numbers will continue to refresh rapidly, ensuring real-time inventory. We may adjust that interval in production, but that seemed fast enough for our purposes.

Code for Inventory.js:

import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import algoliasearch from 'algoliasearch';
 
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
 
function Inventory({ objectIDs }) {
 const index = searchClient.initIndex('inventory_index');
 let results = index.getObjects(objectIDs);
 useEffect(() => {
   const timer = setInterval(() => {
     results = index.getObjects(objectIDs);
   }, 2000);
   return () => clearTimeout(timer);
 }, []);
 return (
   <ol>
     {results.map(result => (
       <li key={result.objectID}>Remaining: {result.remaining_editions}</li>
     ))}
   </ol>
 );
}
 
Inventory.propTypes = {
 objectIDs: PropTypes.arrayOf(PropTypes.string),
};
 
export default Inventory;

The code inside the <ProductDetail> component is much the same. That component will fetch most of its data from our product database, a non-Algolia data source. For the inventory number, it will call the inventory_index just as above, using only the objectID of the selectedObject. With this design, there should only be a very small lag, no more than two seconds, between the inventory number shown next to the product result in <Hits> and the inventory number in the <ProductDetail> component. With this in place, <ProductDetail> will always show the more recent data. 

Now we have a <SearchPage> that shows near-instant inventory updates, while still allowing full use of as-you-type instant search results.

We envisioned this project as a way for independent artists and musicians to connect their social media presences with an ecommerce platform. As music fans ourselves, we’ve missed the sense of community and energy of the local music scene over the last couple of years. Our hope is that this site design will feel authentic and exciting enough to capture some of that energy. 

Algolia’s quick-to-implement widgets and adaptable components make it easy to spin up prototypes. You may have other ideas of where an ‘instant inventory’ would be useful – Black Friday sales, maybe! We hope to hear about what you build with Algolia, and how it transforms your projects!

About the author
Julia Seidman

Developer Educator

linkedin

Recommended Articles

Powered byAlgolia Algolia Recommend

Adding trending recommendations to your existing e-commerce store
engineering

Ashley Huynh

Part 4: Supercharging search for ecommerce solutions with Algolia and MongoDB — Frontend implementation and conclusion
engineering

Soma Osvay

Full Stack Engineer, Starschema

Building a Store Locator in React using Algolia, Mapbox, and Twilio – Part 2
engineering

Clément Sauvage

Software Engineer, Freelance