Implement highlighting
Solr support highlighting out-of-the box for all fields that are stored. The org.hippoecm.hst.solr.content.beans.query.Hit supports easy fetching of all the highlighting fields for a search hit through getHighlights()
public interface Hit extends Serializable {
SolrDocument getDoc();
/**
* @return the {@link org.hippoecm.hst.content.beans.standard
* .IdentifiableContentBean}
* @throws BindingException when the {@link SolrDocument} bound to
* the {@link org.hippoecm.hst.content.beans.standard
* .IdentifiableContentBean}
*/
IdentifiableContentBean getBean() throws BindingException;
/**
* @return the score for this hit and -1 if there is no score available
*/
float getScore();
/**
* @return the {@link List} of {@link Highlight}s and empty List if
* there are no highlights
*/
public List<Highlight> getHighlights();
}
Enable highlighting
Thus, make sure, that the fields you want highlighting on are stored. In your Solr schema.xml, for example have
<field name="title" type="text_general" indexed="true" stored="true" /> <field name="summary" type="text_general" indexed="true" stored="true"/>
and in your java code, set highlighting switched on through:
@Override
public void doBeforeRender(final HstRequest request,
final HstResponse response)
throws HstComponentException {
HippoSolrClient solrClient =
HstServices.getComponentManager().getComponent(
HippoSolrClient.class.getName(), "org.hippoecm.hst.solr");
HippoQuery hippoQuery = solrClient.createQuery(query);
hippoQuery.getSolrQuery().setHighlight(true);
hippoQuery.getSolrQuery().setHighlightFragsize(150);
hippoQuery.getSolrQuery().setHighlightSimplePre("<b style=\"color:blue\">");
hippoQuery.getSolrQuery().setHighlightSimplePost("</b>");
// hippoQuery.getSolrQuery().addHighlightField("title");
// hippoQuery.getSolrQuery().addHighlightField("summary");
// hippoQuery.getSolrQuery().addHighlightField("htmlContent");
// highlight in any fetched field
hippoQuery.getSolrQuery().addHighlightField("*");
HippoQueryResult result = hippoQuery.execute();
request.setAttribute("result", result);
}
In your JSP code, you can now access the highlights as follows:
<c:forEach var="hit" items="${requestScope.result.hits}">
<c:set var="bean" value="${hit.bean}"/>
<hst:link var="link" hippobean="${bean}"/>
<ul class="list-overview">
<li class="title"><b><a href="${link}">${bean.title}</a></b>
<div>
<c:forEach var="highlight" items="${hit.highlights}">
<c:forEach var="excerpt" items="${highlight.excerpts}">
<p>
${excerpt}
</p>
</c:forEach>
</c:forEach>
</div>
</li>
</ul>
</c:forEach>