How backend search works
InstantSearch is the UI on top of a search client. Its state is managed by the Algolia search helper. However, you can use a different search client.Algolia search client
Algolia’s search client queries Algolia’s backend whenever users refine the search. The response from Algolia’s search client is a JSON object that includes:- Results already formatted for display (full record content, embedded HTML, image URLs, and so on).
- Highlighting and snippeting
- Pagination
Custom search client
You can implement your own search client to query your backend which, in turn, uses the Algolia search client to query Algolia’s backend. To create your own client, you must implement an interface that receives and returns formatted data that InstantSearch can understand.On the backend: create the necessary routes
This guide assumes that you have an existing server running on http://localhost:3000 with the routePOST /search
that takes the default Algolia query parameters as JSON. This backend could be using the JavasScript API client to query Algolia, on top of any other operations you want to perform.
The algoliasearch
package lets you query Algolia from your backend. Here’s an example using Express:
JavaScript
On the frontend: call your new backend routes
Searching for results
A search client implements thesearch()
method every time users search and refine results.
Since the server accepts the InstantSearch format as an input, you only need to pass these requests to your backend in this method and return the response.
JavaScript
search()
and getRecommendations()
methods support:
Search for facet values
The samesearch()
method is used by InstantSearch to fetch facet values from refinement lists.
You must set the option
searchable
to true
in your refinement list to make it searchable.Use the search client with InstantSearch
Now, you need to tell InstantSearch to use the search client you created. This is possible with thesearchClient
option.
This parameter turns off all Algolia requests coming from the frontend and proxies them to your backend and displays the UI.
JavaScript
Enrich data from the backend
Now that InstantSearch is querying your backend before fetching results from Algolia, you could merge Algolia’s data with yours (to offer your users more exhaustive results). A recurring problem with ecommerce websites using Algolia managing the remaining stock for each product. It’s sometimes hard to keep track of the exact number of items. An approach made possible with a custom backend is to only store the item’s availability on each Algolia record (none
, low
, medium
, high
) and to fetch the exact stock on your database.
You need to make a few changes to your backend:
JavaScript
stock
on each hit with InstantSearch on the frontend.