Search code examples
solrsolrj

How do I get Highlighted Snippets using SolrJ?


I am migrating my application from Lucene to Solr. Solr handles highlighting a lot better, however if for instance I search the key word "city", I would expect a response like:

{
   "id":"fdc3833a-0e4f-4314-ba8c",
   "title": "Paris is a beautiful <b>city</b>",
   "description": "The <b>city</b> is a great example of......",
}

while I am getting the following response instead:

{
       "id":"fdc3833a-0e4f-4314-ba8c",
       "title": "Paris is a beautiful city",
       "description": "The city is a great example of......",
    }
    "highlighting": {
        "fdc3833a-0e4f-4314-ba8c": {
              "title": [
                "Paris is a beautiful <b>city</b>"
              ],
              "description": [
                "The <b>city</b> is a great example of......"
              ]
            }
        }

So as you can see, instead of getting the highlighted term within the result, I am getting an extra section called highlighting and that means that my Java code has to change. My question is: how will I get the highlight snippets in SolrJ?


Solution

  • In SolrJ is possible to get the highlighted snippets using the following code:

    public String getHighlightedText(final QueryResponse queryResponse, final String fieldName, final String docId) {
        String highlightedText = "";
        Map<String, Map<String, List<String>>> highlights = queryResponse.getHighlighting();
        if (highlights!=null && MapUtils.isNotEmpty(highlights.get(docId))) {
            List<String> snippets = highlights.get(docId).get(fieldName);
            if (CollectionUtils.isNotEmpty(snippets)) {
                highlightedText = getFragments(snippets);
            }
        }
    return highlightedText;
    }
    
    private static final String getFragments(List<String> snippets){
            StringBuilder fragments = new StringBuilder();
            for (int i = 0; i < snippets.size(); i++) {
                if (i > 0) {
                    fragments.append("............");
                }
                fragments.append(snippets.get(i));
            }
            return fragments.toString();
        }
    

    Please notice that this code will get you the best snippets for single-value fields while you will need some variations for multi-value fields.