Search by Algolia
Add InstantSearch and Autocomplete to your search experience in just 5 minutes
product

Add InstantSearch and Autocomplete to your search experience in just 5 minutes

A good starting point for building a comprehensive search experience is a straightforward app template. When crafting your application’s ...

Imogen Lovera

Senior Product Manager

Best practices of conversion-focused ecommerce website design
e-commerce

Best practices of conversion-focused ecommerce website design

The inviting ecommerce website template that balances bright colors with plenty of white space. The stylized fonts for the headers ...

Catherine Dee

Search and Discovery writer

Ecommerce product listing pages: what they are and how to optimize them for maximum conversion
e-commerce

Ecommerce product listing pages: what they are and how to optimize them for maximum conversion

Imagine an online shopping experience designed to reflect your unique consumer needs and preferences — a digital world shaped completely around ...

Vincent Caruana

Senior Digital Marketing Manager, SEO

DevBit Recap: Winter 2023 — Community
engineering

DevBit Recap: Winter 2023 — Community

Winter is here for those in the northern hemisphere, with thoughts drifting toward cozy blankets and mulled wine. But before ...

Chuck Meyer

Sr. Developer Relations Engineer

How to create the highest-converting product detail pages (PDPs)
e-commerce

How to create the highest-converting product detail pages (PDPs)

What if there were a way to persuade shoppers who find your ecommerce site, ultimately making it to a product ...

Vincent Caruana

Senior Digital Marketing Manager, SEO

Highlights from GopherCon Australia 2023
engineering

Highlights from GopherCon Australia 2023

This year a bunch of our engineers from our Sydney office attended GopherCon AU at University of Technology, Sydney, in ...

David Howden
James Kozianski

David Howden &

James Kozianski

Enhancing customer engagement: The role of conversational commerce
e-commerce

Enhancing customer engagement: The role of conversational commerce

Second only to personalization, conversational commerce has been a hot topic of conversation (pun intended) amongst retailers for the better ...

Michael Klein

Principal, Klein4Retail

Craft a unique discovery experience with AI-powered recommendations
product

Craft a unique discovery experience with AI-powered recommendations

Algolia’s Recommend complements site search and discovery. As customers browse or search your site, dynamic recommendations encourage customers to ...

Maria Lungu

Frontend Engineer

What are product detail pages and why are they critical for ecommerce success?
e-commerce

What are product detail pages and why are they critical for ecommerce success?

Winter is coming, along with a bunch of houseguests. You want to replace your battered old sofa — after all,  the ...

Catherine Dee

Search and Discovery writer

Why weights are often counterproductive in ranking
engineering

Why weights are often counterproductive in ranking

Search is a very complex problem Search is a complex problem that is hard to customize to a particular use ...

Julien Lemoine

Co-founder & former CTO at Algolia

How to increase your ecommerce conversion rate in 2024
e-commerce

How to increase your ecommerce conversion rate in 2024

2%. That’s the average conversion rate for an online store. Unless you’re performing at Amazon’s promoted products ...

Vincent Caruana

Senior Digital Marketing Manager, SEO

How does a vector database work? A quick tutorial
ai

How does a vector database work? A quick tutorial

What’s a vector database? And how different is it than a regular-old traditional relational database? If you’re ...

Catherine Dee

Search and Discovery writer

Removing outliers for A/B search tests
engineering

Removing outliers for A/B search tests

How do you measure the success of a new feature? How do you test the impact? There are different ways ...

Christopher Hawke

Senior Software Engineer

Easily integrate Algolia into native apps with FlutterFlow
engineering

Easily integrate Algolia into native apps with FlutterFlow

Algolia's advanced search capabilities pair seamlessly with iOS or Android Apps when using FlutterFlow. App development and search design ...

Chuck Meyer

Sr. Developer Relations Engineer

Algolia's search propels 1,000s of retailers to Black Friday success
e-commerce

Algolia's search propels 1,000s of retailers to Black Friday success

In the midst of the Black Friday shopping frenzy, Algolia soared to new heights, setting new records and delivering an ...

Bernadette Nixon

Chief Executive Officer and Board Member at Algolia

Generative AI’s impact on the ecommerce industry
ai

Generative AI’s impact on the ecommerce industry

When was your last online shopping trip, and how did it go? For consumers, it’s becoming arguably tougher to ...

Vincent Caruana

Senior Digital Marketing Manager, SEO

What’s the average ecommerce conversion rate and how does yours compare?
e-commerce

What’s the average ecommerce conversion rate and how does yours compare?

Have you put your blood, sweat, and tears into perfecting your online store, only to see your conversion rates stuck ...

Vincent Caruana

Senior Digital Marketing Manager, SEO

What are AI chatbots, how do they work, and how have they impacted ecommerce?
ai

What are AI chatbots, how do they work, and how have they impacted ecommerce?

“Hello, how can I help you today?”  This has to be the most tired, but nevertheless tried-and-true ...

Catherine Dee

Search and Discovery 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