Highlight Search Results


  • When making a Full-Text Search query,
    in addition to retrieving documents that contain the searched terms in the results,
    you can also request to get a list of text fragments that highlight the searched terms.

  • The highlighted terms can enhance user experience when searching for documents with specific content.

  • This article shows highlighting search results when making a dynamic-query.
    For highlighting search results when querying a static-index see highlight index search results.



Highlight - basic example

// Make a full-text search dynamic query:
// ======================================

// Define a param that will get the highlighted text fragments
let salesHighlights;

const employeesResults = await session
     // Make a dynamic query on 'Employees' collection
    .query({ collection: "Employees" })
     // Search for documents containing the term 'sales' in their 'Notes' field
    .search("Notes", "sales")
     // Request to highlight the searched term by calling 'highlight'
    .highlight({ 
        fieldName: 'Notes', // The document-field name in which we search 
        fragmentLength: 35, // Max length of each text fragment
        fragmentCount: 4 }, // Max number of fragments to return per document
        x => { salesHighlights = x; }) // Output param 'salesHighlights' will be filled
                                       // with the highlighted text fragments when query returns. 
     // Execute the query
    .all();
from "Employees"
where search(Notes, "sales")
include highlight(Notes, 35, 4)

// Process results:
// ================

// 'employeesResults' contains all Employee DOCUMENTS that have 'sales' in their 'Notes' field.
// 'salesHighlights' contains the text FRAGMENTS that highlight the 'sales' term.

let fragmentsHtml = "<ul>";

employeesResults.forEach((employee) => {
    // Call 'getFragments' to get all fragments for the specified employee id
    let fragments = salesHighlights.getFragments(employee.id);
    
    fragments.forEach((fragment) => {
        fragmentsHtml += `<li>Doc: ${employee.id} Fragment: ${fragment}</li>`;
    });
});

fragmentsHtml += "</ul>";

// The resulting fragmentsHtml:
// ============================

// <ul>
//   <li>Doc: employees/2-A Fragment: company as a <b style="background:yellow">sales</b></li>
//   <li>Doc: employees/2-A Fragment: promoted to <b style="background:yellow">sales</b> manager in</li>
//   <li>Doc: employees/2-A Fragment: president of <b style="background:yellow">sales</b> in March 1993</li>
//   <li>Doc: employees/2-A Fragment: member of the <b style="background:yellow">Sales</b> Management</li>
//   <li>Doc: employees/3-A Fragment: hired as a <b style="background:yellow">sales</b> associate in</li>
//   <li>Doc: employees/3-A Fragment: promoted to <b style="background:yellow">sales</b> representativ</li>
//   <li>Doc: employees/5-A Fragment: company as a <b style="background:yellow">sales</b> representativ</li>
//   <li>Doc: employees/5-A Fragment: promoted to <b style="background:yellow">sales</b> manager in</li>
//   <li>Doc: employees/5-A Fragment: <b style="background:yellow">Sales</b> Management." </li>
//   <li>Doc: employees/6-A Fragment: for the <b style="background:yellow">Sales</b> Professional.</li>
// </ul>

Highlight tags


  • By default, the highlighted term is wrapped with the following html:
    <b style="background:yellow">term</b>

  • When requesting to highlight multiple terms,
    the background color returned for each different term will be in the following order:

    •  yellow,
    •  lawngreen,
    •  aquamarine,
    •  magenta,
    •  palegreen,
    •  coral,
    •  wheat,
    •  khaki,
    •  lime,
    •  deepskyblue,
    •  deeppink,
    •  salmon,
    •  peachpuff,
    •  violet,
    •  mediumpurple,
    •  palegoldenrod,
    •  darkkhaki,
    •  springgreen,
    •  turquoise,
    •  powderblue
  • The html tags that wrap the highlighted terms can be customized to any other tags.
    See customize tags below.

Highlight results in Studio


Figure 1. Fragments results

View highlighted fragments in the Query View

  1. Auto-Index
    This is the auto-index that was created by the server to serve the dynamic-query.

  2. Results tab
    The results tab contains the resulting documents that match the provided RQL query.

  3. Highlight tab
    The highlight tab shows the resulting fragments that were included in the query result.

Highlight - customize tags

  • The html tags that wrap the highlighted terms can be customized to any other tags.

// Define customized tags to use for highlighting the searched terms
// =================================================================
const tagsToUse = {
    preTags: ["+++", "<<<"],
    postTags: ["+++", ">>>"]
};

// Make a full-text search dynamic query:
// ======================================
let salesHighlights;
let managerHighlights;

const employeesResults = await session
    .query({ collection: "Employees" })
     // Search for:
     //   * documents containing the term 'sales' in their 'Notes' field
     //   * OR for documents containing the term 'manager' in their 'Title' field
    .search("Notes", "sales")
    .search("Title", "manager")
     // Call 'highlight' for each field searched
     // Pass 'tagsToUse' to OVERRIDE the default tags used 
    .highlight({ fieldName: 'Notes', fragmentLength: 35, fragmentCount: 1, ...tagsToUse },
            x => { salesHighlights = x; })
    .highlight({ fieldName: 'Title', fragmentLength: 35, fragmentCount: 1, ...tagsToUse },
            x => { managerHighlights = x; })
    .all();
from "Employees"
where (search(Notes, "sales") or search(Title, "manager"))
include highlight(Notes, 35, 1, $p0), highlight(Title, 35, 1, $p1)
{
"p0":{"PreTags":["+++","<<<"],"PostTags":["+++",">>>"]},
"p1":{"PreTags":["+++","<<<"],"PostTags":["+++",">>>"]}
}

// The resulting salesHighlights fragments:
// ========================================

// "for the +++Sales+++ Professional."
// "hired as a +++sales+++ associate in"
// "company as a +++sales+++"
// "company as a +++sales+++ representativ"

// The resulting managerHighlights fragments:
// ==========================================

// "Sales <<<Manager>>>"        

Highlight - projected results

// Make a full-text search dynamic query & project results:
// ========================================================

// Define a param that will get the highlighted text fragments
let termsHighlights;

// Define the class for the projected results
class Result {
    constructor () {
        this.Name = null;
        this.Title = null;
    }
}

// Make a dynamic query on 'Employees' collection
const employeesResults = await session
    .query({ collection: "Employees" })
     // Search for documents containing 'sales' or 'german' in their 'Notes' field
    .search("Notes", "manager german")
     // Request to highlight the searched terms from the 'Notes' field 
    .highlight({ fieldName: "Notes", fragmentLength: 35, fragmentCount: 2 },
            x => { termsHighlights = x; })
     // Define the projection
    .selectFields(QueryData.customFunction("o", "{ Name: o.FirstName + ' ' + o.LastName, Title: o.Title }" ),
        Result)
    .all();
from "Employees" as x
where search(x.Notes, "manager german")
select { Name : "{0} {1}".format(x.FirstName, x.LastName), Title : x.Title }
include highlight(Notes, 35, 2)

// The resulting fragments from termsHighlights:
// =============================================

// "to sales <b style=\"background:yellow\">manager</b> in March"
// "and reads <b style=\"background:lawngreen\">German</b>.  He joined"
// "to sales <b style=\"background:yellow\">manager</b> in January"
// "in French and <b style=\"background:lawngreen\">German</b>."

// NOTE: each search term is wrapped with a different color
// 'manager' is wrapped with yellow
// 'german' is wrapped with lawngreen

Syntax

highlight(parameters, hightlightingsCallback);
Parameter Type Description
parameters HighlightingParameters Parameters for the highlight method.
hightlightingsCallback (highlightResults) => void) A callback function with an output parameter.
The parameter passed to the callback will be filled with the Highlightings object when query returns.


The Highlighting parameters:

Parameter Type Description
fieldName string Name of the field that contains the searched terms to highlight.
fragmentLength number Maximum length of a text fragment. Must be >= 18.
fragmentCount number Maximum number of text fragments that will be returned.
groupKey string Grouping key for the results.
Used when highlighting query results from a Map-Reduce index.
If null results are grouped by document ID (default).
Note: Highlighting is Not available for dynamic aggregation queries.
preTags string[] Array of PRE tags used to wrap the highlighted search terms in the text fragments.
postTags string[] Array of POST tags used to wrap the highlighted search terms in the text fragments.


The Highlightings object:

class Highlightings {
    // Name of the field that contains the searched terms to highlight.
    get fieldName();
    // The resulting keys (document IDs, or the map-reduce keys)
    get resultIndents();
    // Returns the list of the highlighted text fragments for the passed document ID, or the map-reduce key
    getFragments(key);
}