Search by Algolia
What is a multi-vendor marketplace, and how to build one?
e-commerce

What is a multi-vendor marketplace, and how to build one?

Want to be the next Amazon? How about a follow-on to Etsy that adds a unique twist? We all ...

Catherine Dee

Search and Discovery writer

What is end-to-end AI search?
ai

What is end-to-end AI search?

Simplicity is critical for search engines, but building one that enables that simplicity is complex.  Over the last 20+ years ...

Abhijit Mehta

Director of Product Management

Comparing AI search solutions in a crowded market landscape
ai

Comparing AI search solutions in a crowded market landscape

Many new AI-powered search solutions have been released this year, and each promises to provide great results, but as ...

Andy Jones

Marketing Campaign Production Manager

What is B2B ecommerce? Everything you need to know
e-commerce

What is B2B ecommerce? Everything you need to know

When you think of “customer experience,” what comes to mind? People, right? Specifically, consumers. Retail customers. That’s easy; the ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

What is ecommerce merchandising? Key components and best practices
e-commerce

What is ecommerce merchandising? Key components and best practices

A potential customer is about to land on the home page of your ecommerce platform, curious to see what cool ...

Catherine Dee

Search and Discovery writer

AI-powered search: From keywords to conversations
ai

AI-powered search: From keywords to conversations

By now, everyone’s had the opportunity to experiment with AI tools like ChatGPT or Midjourney and ponder their inner ...

Chris Stevenson

Director, Product Marketing

Vector vs Keyword Search: Why You Should Care
ai

Vector vs Keyword Search: Why You Should Care

Search has been around for a while, to the point that it is now considered a standard requirement in many ...

Nicolas Fiorini

Senior Machine Learning Engineer

What is AI-powered site search?
ai

What is AI-powered site search?

With the advent of artificial intelligence (AI) technologies enabling services such as Alexa, Google search, and self-driving cars, the ...

John Stewart

VP Corporate Marketing

What is a B2B marketplace?
e-commerce

What is a B2B marketplace?

It’s no secret that B2B (business-to-business) transactions have largely migrated online. According to Gartner, by 2025, 80 ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

3 strategies for B2B ecommerce growth: key takeaways from B2B Online - Chicago
e-commerce

3 strategies for B2B ecommerce growth: key takeaways from B2B Online - Chicago

Twice a year, B2B Online brings together industry leaders to discuss the trends affecting the B2B ecommerce industry. At the ...

Elena Moravec

Director of Product Marketing & Strategy

Deconstructing smart digital merchandising
e-commerce

Deconstructing smart digital merchandising

This is Part 2 of a series that dives into the transformational journey made by digital merchandising to drive positive ...

Benoit Reulier
Reshma Iyer

Benoit Reulier &

Reshma Iyer

The death of traditional shopping: How AI-powered conversational commerce changes everything
ai

The death of traditional shopping: How AI-powered conversational commerce changes everything

Get ready for the ride: online shopping is about to be completely upended by AI. Over the past few years ...

Aayush Iyer

Director, User Experience & UI Platform

What is B2C ecommerce? Models, examples, and definitions
e-commerce

What is B2C ecommerce? Models, examples, and definitions

Remember life before online shopping? When you had to actually leave the house for a brick-and-mortar store to ...

Catherine Dee

Search and Discovery writer

What are marketplace platforms and software? Why are they important?
e-commerce

What are marketplace platforms and software? Why are they important?

If you imagine pushing a virtual shopping cart down the aisles of an online store, or browsing items in an ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

What is an online marketplace?
e-commerce

What is an online marketplace?

Remember the world before the convenience of online commerce? Before the pandemic, before the proliferation of ecommerce sites, when the ...

Catherine Dee

Search and Discovery writer

10 ways AI is transforming ecommerce
e-commerce

10 ways AI is transforming ecommerce

Artificial intelligence (AI) is no longer just the stuff of scary futuristic movies; it’s recently burst into the headlines ...

Catherine Dee

Search and Discovery writer

AI as a Service (AIaaS) in the era of "buy not build"
ai

AI as a Service (AIaaS) in the era of "buy not build"

Imagine you are the CTO of a company that has just undergone a massive decade long digital transformation. You’ve ...

Sean Mullaney

CTO @Algolia

By the numbers: the ROI of keyword and AI site search for digital commerce
product

By the numbers: the ROI of keyword and AI site search for digital commerce

Did you know that the tiny search bar at the top of many ecommerce sites can offer an outsized return ...

Jon Silvers

Director, Digital Marketing

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