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:
// ======================================

$highlightings = new Highlightings();

/** @var array<Employee> $employeesResults */
$employeesResults = $session
    // Make a dynamic query on 'Employees' collection
    ->query(Employee::class)
    // Search for documents containing the term 'sales' in their 'Notes' field
    ->search("Notes", "sales")
    // Request to highlight the searched term by calling 'highlight()'
    ->highlight(
        "Notes", // The document-field name in which we search
        35,           // Max length of each text fragment
        4,            // Max number of fragments to return per document
        null,           // Put null to use default options
        $highlightings) // An out param for getting the highlighted text fragments

    // Execute the query
    ->toList();
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.

$builder = '<ul>';

/** @var SearchItem $employee */
foreach ($employeesResults as $employee) {
    // Call 'GetFragments' to get all fragments for the specified employee Id
    $fragments = $highlightings->getFragments($employee->getId());
    foreach ($fragments as $fragment) {
        $builder .= '<li>Doc: ' . $employee->getId() . ' Fragment: ' . $fragment . '</li>';
    }
}

$builder .= '</ul>';
$fragmentsHtml = $builder;

// 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
// =================================================================

$salesHighlights = new Highlightings();
$managerHighlights = new Highlightings();

$tagsToUse = new HighlightingOptions();
// Provide strings of your choice to 'PreTags' & 'PostTags', e.g.:
// the first term searched for will be wrapped with '+++'
// the second term searched for will be wrapped with '<<<' & '>>>'
$tagsToUse->setPreTags(["+++", "<<<"]);
$tagsToUse->setPostTags(["+++", ">>>"]);

// Make a full-text search dynamic query:
// ======================================
$employeesResults = $session
    ->query(Employee::class)
    // 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("Notes", 35, 1, $tagsToUse, $salesHighlights)
    ->highlight("Title", 35, 1, $tagsToUse, $managerHighlights)
    ->toList();
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:
// ========================================================
$termsHighlights = new Highlightings();

/** @var array<Employee> $employeesProjectedResults */
$employeesProjectedResults = $session
    ->query(Employee::class)
    // 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("Notes", 35, 2, null, $termsHighlights)
    // Define the projection
    ->selectFields(EmployeeDetails::class, QueryData::customFunction("o", "{ name: o.FirstName + ' ' + o.LastName, title: o.Title }"))
    ->toList();
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

function highlight(
    ?string              $fieldName,
    int                  $fragmentLength,
    int                  $fragmentCount,
    ?HighlightingOptions $options,
    Highlightings        &$highlightings
): DocumentQueryInterface;
Parameter Type Description
$fieldName ?string Name of the field that contains the searched terms to highlight
$fragmentLength int Maximum length of a text fragment
Must be >= 18
$fragmentCount int Maximum number of text fragments that will be returned
$options ?HighlightingOptions Customizing options
&$highlightings Highlightings A callback function to retrieve the highlighted text fragments for each returned result


Highlighting options:

private ?string $groupKey;
private ?StringArray $preTags = null;
private ?StringArray $postTags = null;

// getters and setters
Option Type Description
$groupKey ?string Grouping key for the results.
Used when highlighting query results from a Map-Reduce index.
If None results are grouped by document ID (default).
Note: Highlighting is Not available for dynamic aggregation queries.
$preTags ?StringArray Array of PRE tags used to wrap the highlighted search terms in the text fragments.
$postTags ?StringArray Array of POST tags used to wrap the highlighted search terms in the text fragments.


Highlightings object:

private ?string $fieldName = null;
public function getResultIndents(): array;
Property Type Description
$fieldName ?string Name of the field that contains the searched terms to highlight
getResultIndents() function returning an array The resulting keys (document IDs, or the map-reduce keys)

public function getFragments(?string $key): array;
Method Return Type Description
getFragments(?string $key) function returning an array Returns the list of the highlighted text fragments for the passed document ID, or the map-reduce key