Highlight Keywords in Query Results using the Instantsearch JS Hits Widget

Raphael Terrier
InstructorRaphael Terrier
Share this video with your friends

Social Share Links

Send Tweet

Every good search UX make users understand instantly why a given hit is being displayed as part of the result set. One way to achieve that is to highlight the keywords from the query directly inside the Hits. This is built in the API JSON response and in this video we’ll explain how to leverage it easily.

Instructor: [00:00] Here, when we type this query, it's not instantly obvious why those results are there. By looking long enough, we can finally spot that the match occurred in the description. This is not optimal.

[00:12] To fight that issue, a simple way to make results relevance obvious to your user is to implement highlighting. The goal is simple. Style differently parts of the hits that are matching the query so that they stand out from the rest of the hits information.

[00:27] Thankfully, Algolia does a big part of the job for us. Let's take a look at the JSON response here, typing A. For each query, we get, in addition to hits and facets, the highlight result object. Highlighting can be enabled in the specific subset of searchable attributes. By default, it's activated on all of them.

[00:48] Here, we see all of our searchable attributes -- brand, categories, descriptions, name, and type. Let's look at how a single attribute is composed.

[00:59] Opening the name attribute, here we get four elements. The one that really matters to us for the moment is the value. This is where the searchable attribute initial value will be returned, modified with the ais-highlight markers enclosing the matching parts. Those markers are then replaced by the library with a tag of your choosing, by default, the mark tag. Here, we'll keep the default.

[01:25] To display highlighted results, there's a couple of things we need to do. First, we need to create a CSS rule for our mark tag. This has already been done in our style.css file. Let's first highlight the name.

[01:39] Instead of accessing them directly through their attributes, we will leverage the Instant.Search highlight method, passing it the attribute and the hit data. Saving and reloading the page, now typing a few queries, we have highlighting visible on the name and we can now tell immediately what results are matching and where.

[02:01] Let's repeat the same process for the description. Now we have a search page with fully functional highlighting, simply by tweaking a little our existing template.