Search by Algolia
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

What is ecommerce? The complete guide
e-commerce

What is ecommerce? The complete guide

How well do you know the world of modern ecommerce?  With retail ecommerce sales having exceeded $5.7 trillion worldwide ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Data is king: The role of data capture and integrity in embracing AI
ai

Data is king: The role of data capture and integrity in embracing AI

In a world of artificial intelligence (AI), data serves as the foundation for machine learning (ML) models to identify trends ...

Alexandra Anghel

Director of AI Engineering

What are data privacy and data security? Why are they  critical for an organization?
product

What are data privacy and data security? Why are they critical for an organization?

Imagine you’re a leading healthcare provider that performs extensive data collection as part of your patient management. You’re ...

Catherine Dee

Search and Discovery writer

Achieving digital excellence: Algolia's insights from the GDS Retail Digital Summit
e-commerce

Achieving digital excellence: Algolia's insights from the GDS Retail Digital Summit

In an era where customer experience reigns supreme, achieving digital excellence is a worthy goal for retail leaders. But what ...

Marissa Wharton

Marketing Content Manager

AI at scale: Managing ML models over time & across use cases
ai

AI at scale: Managing ML models over time & across use cases

Just a few years ago it would have required considerable resources to build a new AI service from scratch. Of ...

Benoit Perrot

VP, Engineering

Looking for something?

facebookfacebooklinkedinlinkedintwittertwittermailmail

Visually highlighting search results is a must-have component of a great search experience. This is even truer when you start to do advanced processing on the query (synonyms, typo tolerance, concatenation/split of query words, etc.), like we presented in the third installment of this series.

A search result that is considered as weird by a user without highlighting can become smart just by explaining the processing done to retrieve it and by making it easy for the user to check if this is exactly the content they were looking for. In this article, we’ll show you in detail how we have implemented our highlighting to make sure it always provides a great user experience.

Google search query with highlighting removed on second hitOn this Google query, the first hit shows the standard highlighting done by Google. We removed the highlighting manually on the second hit – the result is much more difficult to understand.

Different approaches

Highlighting tends to be a subject that appears easy at first glance; however, the reality is much more complex, namely because it is a different process entirely than that of matching & ranking your objects. There are three main ways to implement highlighting:

  1. Take the query and the text to highlight and imitate the job of the search engine. This approach is partial as you don’t have access to the processing done by the search engine like the extraction of synonyms. Usually this means that you just highlight the query terms, which will be misleading for users as they will not see why a record was found.
  2. Apply the query interpreter on the query to extract all possible extensions like synonyms and use that information to highlight a text. This approach will give you a good visual result as you will have all the alternatives. But you will have to test a lot of expressions that do not match against your text. There is a lot of waste of performance here.
  3. Apply the query in the search engine as usual but keep the matched terms for each result. This list of matched terms will be used by the highlighter to process a record. This approach offers the best of two worlds: you have exactly the expected highlight whereas the highlighter remains fast and only focuses on the expression that is in the record.

The big advantage of the last two approaches is that your highlighter will be easier to implement. You don’t have to worry about alternatives like synonyms or typo-tolerance as it will already be resolved by your query interpreter. In other words, if your record matches with a typo, you will have the word with a typo as an input of the highlighter.

In the Algolia engine, we have used the third approach since day one. It was actually one of the many reasons to redevelop the Algolia engine from scratch. We had already developed several highlighters in the past and we knew from experience the third approach would be the best; however, we had to to keep all matched terms for each record, which needs to be done in a very efficient way in order to not create a bottleneck in term of CPU or RAM.

Different expressions we highlight

There are four types of expression that the highlighter can highlight:

  1. A word: in this case, we need to find all tokens in the text to highlight that are identical to this word (with an accent and case-insensitive comparison).
  2. A prefix: in this case, we need to find all tokens in the text to highlight that start with this prefix (again with an accent and case-insensitive comparison). Usually, this word corresponds to the last query term that is matched as a prefix; however, it can also contain a typo (as we support typo tolerance on prefixes).
  3. A phrase: in this case, we need to find a sequence of words in a specific order in the record (also with an accent and case-insensitive comparison).
  4. A prefix phrase: identical as a phrase, except that the last word of the phrase can be matched via a prefix.

All those expressions come from the search engine and are an input for the highlighter, for example the user query “searchengine” contains only one term but will also add the alternative phrase “search engine” which is the result of our split of query tokens processing (described in the third article of this series).

Explaining the result using query terms

The highlighter is not just the process that adds some tags around matching expressions, it plays a bigger role in the user experience. You have potentially dozens of attributes in your objects used for search, displaying all of them would give too much information to the user. You only have to show the relevant one to explain the result.

For example, if you are typing the query “Twilio IPO” on your favorite news site, you will have several objects that will match. Some with both terms in the title like this one:

Title: Twilio raises more than expected in IPO
Content: Twilio Inc. raised more than it expected in its initial public offering, an optimistic sign for the dozens of other technology companies that have been valued at more than $1 billion in private fundraising. [...]

And some with only one term in the title like this one:

Title: Twilio’s shares climb 92% in trading debut
Content: Twilio Inc.’s shares nearly doubled from their initial public offering price in their first day of trading, a positive sign during a dry spell for tech IPOs. [...]

On the first one, the highlighter will give you the information that all query terms were found in the title attribute (via the `matchLevel=full`), which allows you to consider a specific display of this article in the UI as only the title is required to explain the result.

Here is the highlighter information on the title of the first article:

{
    "_highlightResult": {
        "title": {
            "value": "Twilio raises more than expected in IPO", 
            "matchLevel": "full", 
            "matchedWords": [
                "twilio", 
                "ipo"
            ]
        }
    }
}

On the second article, the highlighter will give you the information that the title attribute is partially matching the query (“matchLevel=partial”).

{
   "_highlightResult": {
        "title": {
            "value": "Twilio’s shares climb 92% in trading debut", 
            "matchLevel": "partial", 
            "matchedWords": [
                "twilio"
            ]
        }
    }
}

The highlighter gives you all information needed to explain the query, you can scan all attributes in the highlighter and only select the ones that “explain” one query term that no other one explains. Most of the time, you don’t have enough room to show every title and its content, in this case the highlighter will help you to show the content only when it’s relevant to explain the result. This approach of explaining search results plays a big role in user engagement and improvement of your ROI on search.

Movie and actor searchAn example of a search query where several attributes are required to explain the result: the movie title & the actor name.

Computing a snippet

When the text of an attribute contains more than a few words like the content of a news article, you want to summarize it by keeping only the important sections. The result of this process is called a snippet and there are a lot of different approaches, so every snippet computation is different.

In Algolia, the snippet computation relies on the highlighting.

The first step of the process is to flag each token of the text to snippet with the corresponding query term that matches it. Then the second step is to find the window of N tokens that maximise the number of different query terms matched. You can have several windows of N tokens that contains the same number of highlighted terms, in this case we prefer to leave some text before and after the matching terms to give some context to the user.

Algolia lets you customize the number of words in a snippet, as this parameter depends on the UI you are building. In the example below, we will use 10 words for the  description of the two articles:

{
   "_snippetResult": {
        "content": "Twilio Inc. raised more than it expected in its initial…", 
        "matchLevel": "partial"
    }
}
{
   "_snippetResult": {
        "content": "Twilio Inc.’s shares nearly doubled from their initial public offering…", 
        "matchLevel": "partial"
    }
}

The two snippets actually return the 10 first words of the content as there is no 10 words window that contains both terms.

You can note that we do not return matchedWords attribute in the snippet as the result is partial. You need to use the highlighter to fully explain a result but you can, of course, request to have both the highlighted version and the snippet version.

How the engine identifies matching words efficiently

Our highlighter is exhaustive while having very good performance, a big part of the hard work is actually done in the search engine itself in the identification and storage of all matched words for an object.

During the query processing, we compute all expressions to find and create a description object for each of them that contains the expression to highlight and the link to the original query token. At the end of the query processing, we have a vector with all those alternative expressions.

Then, when we create the boolean query that will be applied to the index, we keep the link to the original expression. For example if you have the query “Hotel NY” with a synonym “NY” = “New York”, the expression vector would be:

0: toHighlight=hotel, queryTerm=hotel
1: toHighlight=NY, queryTerm=ny
2: toHighlight="New York", queryTerm=ny

We would execute the following query:

OR(AND(Word("hotel", vectorPos=0),
       Phrase("New York", vectorPos=2)),
   AND(Word("hotel", vectorPos=0),
       Word("NY", vectorPos=1)))

When a record matches, we know which part of the expression matched (list of integers). For example:

  • A record containing “hotel” and “NY” will have a vector containing [0, 1]
  • A record containing “hotel” and “new york” will have a vector containing [0, 2]
  • A record containing “hotel” and “NY” and “new york” will have a vector containing [0, 1, 2]

This example is very simple as we have a very small number of expressions to match. In reality, we usually have hundreds of expressions to try because of typo tolerance and it becomes critical to identify only the one found in the record.

We finally keep this vector of integers for each result to be able to produce the list of terms to highlight and the list of matched words.

Why search without highlighting is bad

As soon as you have advanced query interpretation,highlighting becomes essential to a good  user experience. Having a great experience is more than highlighting the most important attribute, it is searching and displaying all attributes that are important for the user to understand why the result was displayed. This is key to help the user quickly decide which result they will choose first. Without this aspect, you will leave your user disappointed as they will inevitably choose a bad result.

I hope this explanation has underscored why highlighting is such a complex and important topic of any search engine!

We recommend to read the other posts of this series:

About the author
Julien Lemoine

Co-founder & former CTO at Algolia

githublinkedintwitter

14-day free trial

Create a full-featured search experience in no time.

Get started
14-day free trial

Recommended Articles

Powered byAlgolia Algolia Recommend

Inside the Algolia Engine Part 3 — Query Processing
engineering

Julien Lemoine

Co-founder & former CTO at Algolia

Algolia's top 10 tips to achieve highly relevant search results
product

Julien Lemoine

Co-founder & former CTO at Algolia

Inside the Engine Part 8: Handling Advanced Search Use Cases
engineering

Julien Lemoine

Co-founder & former CTO at Algolia