Highlight the Search Words in Your Results

Solr API

Highlighting sends back, for every result, a short piece of its text with the searched words marked, ready to show under the title.

01 · The parameters

hl=true
hl.method=unified
hl.q={!edismax qf="title description uri text" mm=0 v=$uq}
hl.fl=title,description,text
hl.encoder=html
hl.fragsize=300
hl.snippets=1
hl.defaultSummary=true
f.title.hl.fragsize=0
ParameterWhat it does
hl.qThe words to mark. With the hybrid parser, give the keyword query of the search with mm=0, so that every searched word is marked, and read the words from uq like the search does.
hl.flThe fields to mark. The hosted search page marks uri,title,description,text.
hl.encoder=htmlEscapes <, > and & in the text of the page. Only the <em> tags Solr adds stay as markup. Without it, the snippet comes back as raw text from the page.
hl.fragsizeThe length of a snippet, in characters. f.title.hl.fragsize=0 returns the whole title.
hl.defaultSummaryWhen no searched word is in a field, the start of the field comes back instead, so a result found by meaning still has a snippet.

02 · The response

"highlighting": {
  "8aa72b811b044cdc5be64b1bcdcffa38": {
    "title": ["Solar <em>Panels</em> for Small Roofs"],
    "description": ["How many <em>panels</em> fit on a small roof, and what they produce."]
  }
}

The keys are the id of each document in response.docs. A field with nothing to mark may be missing from its entry: show the stored value instead.

03 · Show it safely

With hl.encoder=html the snippet can go into the page as HTML. The values you show without highlighting, a title with no highlight, the address of the page, must be escaped by your own code.

function esc(s) {
  var d = document.createElement('div');
  d.textContent = s == null ? '' : String(s);
  return d.innerHTML;
}
var hl = (data.highlighting || {})[doc.id] || {};
titleEl.innerHTML = (hl.title && hl.title[0]) || esc(doc.title);
snippetEl.innerHTML = (hl.description && hl.description[0]) || (hl.text && hl.text[0]) || esc(doc.description);
.result em { font-style: normal; font-weight: 700; }

04 · Next

The JSON response

The other parts of the answer.

Complete search page

A page that shows highlighted results, facets and pages.