Search code examples
solrhighlighting

How to highlight text in solr?


I'm new to Solr and I'm using version 4.3.0. I just want to enable basic highlighting. I have created a UI using AJAX-Solr and I'm using the default request handlers. Please guide me from scratch. Also, I want to enable highlighting through the request handlers and not through the query URL parameters. Thanks in advance.


Solution

  • If you are using Ajax-solr you won't use the Solr server highlight parameter.

    Solr-Ajax will create a javascript list with the matching words you type using facet component.

    In other words, if you are using ajax-solr you will need to modify the AutocompleteWidget.js

    You need to modify from the original autocomplete reuters example from line 23 to 33.

    and replace it with this partial code

    $(self.target).find('input').autocomplete('destroy').autocomplete({
            source: function( request, response ) {
    
                var srchTerm = request.term.split(/\s+/).join ('|');
                var matcher = new RegExp( "(" + AjaxSolr.Parameter.escapeValue( srchTerm )+")", "ig" );
                response( $.grep( list, function( item ){
                    return matcher.test( item.value );
                }) );
            },
            select: function(event, ui) {        
              if (ui.item) {
                self.requestSent = true;
                if (self.manager.store.addByValue('fq', ui.item.field + ':' + AjaxSolr.Parameter.escapeValue(ui.item.value))) {
                  self.doRequest();
                }
              }
            }
          }).data('autocomplete')._renderItem = function( ul, item ) {
    
              var srchTerm = this.term.trim().split(/\s+/).join ('|');          
              var strNewLabel = item.label;         
    
              regexp = new RegExp ('(' + srchTerm + ')', "ig");          
              var strNewLabel = strNewLabel.replace(regexp,"<span style='font-weight:bold;color:#880010;'>$1</span>");
    
              return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>" + strNewLabel + ' (' +  item.counter + ') ' + "</a>" )
            .appendTo( ul );
     };
    

    Here is a complete file I used for a project.

    (function (callback) {
      if (typeof define === 'function' && define.amd) {
      define(['../core/AbstractTextWidget'], callback);
      }
      else {
       callback();
      }
    }(function () {
    
    (function ($) {
    
    AjaxSolr.AutocompleteWidget = AjaxSolr.AbstractTextWidget.extend({
      afterRequest: function () {
        $(this.target).find('input').unbind().removeData('events').val('');
    
        var self = this;
    
        var callback = function (response) {
          var list = [];
          for (var i = 0; i < self.fields.length; i++) {
            var field = self.fields[i];
            for (var facet in response.facet_counts.facet_fields[field]) {          
              list.push({
                field: field,
                counter: response.facet_counts.facet_fields[field][facet], 
                value: facet,
                label: facet 
              });
            }
          }
    
          self.requestSent = false;
          $(self.target).find('input').autocomplete('destroy').autocomplete({
            source: function( request, response ) {
    
                var srchTerm = request.term.split(/\s+/).join ('|');
            var matcher = new RegExp( "(" + AjaxSolr.Parameter.escapeValue( srchTerm )+")", "ig" );
            response( $.grep( list, function( item ){
                return matcher.test( item.value );
            }) );
        },
        select: function(event, ui) {        
          if (ui.item) {
            self.requestSent = true;
            if (self.manager.store.addByValue('fq', ui.item.field + ':' + AjaxSolr.Parameter.escapeValue(ui.item.value))) {
                  self.doRequest();
                }
              }
            }
          }).data('autocomplete')._renderItem = function( ul, item ) {
    
              var srchTerm = this.term.trim().split(/\s+/).join ('|');          
              var strNewLabel = item.label;         
    
              regexp = new RegExp ('(' + srchTerm + ')', "ig");          
              var strNewLabel = strNewLabel.replace(regexp,"<span style='font-weight:bold;color:#880010;'>$1</span>");
    
              return $( "<li></li>" )
                .data( "item.autocomplete", item ).append( "<a>" + strNewLabel + ' (' +  item.counter + ') ' + "</a>" )
            .appendTo( ul );
         };
    
          // This has lower priority so that requestSent is set.
          $(self.target).find('input').bind('keydown', function(e) {          
            if (self.requestSent === false && e.which == 13) {
              var value = $(this).val();
              if (value && self.set(value)) {
                self.doRequest();
              }
            }
          });
        } // end callback
    
        var params = [ 'rows=0&facet=true&facet.limit=30&facet.mincount=1&json.nl=map&hl=true&hl.q='+this.manager.store.get('q').val() ];
        var hightLithing='&hl.fl=';
        for (var i = 0; i < this.fields.length; i++) {
          params.push('facet.field=' + this.fields[i]);
          hightLithing = hightLithing + this.fields[i]+',';
        }
        hightLithing.slice(0,-1);
        params.push(hightLithing);
        var values = this.manager.store.values('fq');    
        for (var i = 0; i < values.length; i++) {
          params.push('fq=' + encodeURIComponent(values[i]));      
        }
        params.push('q=' + this.manager.store.get('q').val());
        $.getJSON(this.manager.solrUrl + 'select?' + params.join('&') + '&wt=json&json.wrf=?', {}, callback);
      }//end afterRequest
    });
    
    })(jQuery);
    
    }));