How to highlight text in solr?
Asked Answered
M

3

5

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.

Mystery answered 17/6, 2013 at 6:19 Comment(0)
P
4

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);

}));
Plasticizer answered 23/9, 2013 at 21:14 Comment(0)
T
4

You can directly test the highlighting by passing the highlight parameters.

e.g. hl=true&hl.fl=name,features

Also, you can configure the highlight defaults within you request handler in solrconfig.xml e.g.

<requestHandler name="/browse" class="solr.SearchHandler">
 <lst name="defaults">

    ................

   <!-- Highlighting defaults -->
   <str name="hl">on</str>
   <str name="hl.fl">content features title name</str>
   <str name="hl.encoder">html</str>
   <str name="hl.simple.pre">&lt;b&gt;</str>
   <str name="hl.simple.post">&lt;/b&gt;</str>
   <str name="f.title.hl.fragsize">0</str>
   <str name="f.title.hl.alternateField">title</str>
   <str name="f.name.hl.fragsize">0</str>
   <str name="f.name.hl.alternateField">name</str>
   <str name="f.content.hl.snippets">3</str>
   <str name="f.content.hl.fragsize">200</str>
   <str name="f.content.hl.alternateField">content</str>
   <str name="f.content.hl.maxAlternateFieldLength">750</str>


 </lst>

</requestHandler>
Tarnish answered 17/6, 2013 at 6:34 Comment(2)
Hi, I made the changes as suggested by you but the highlighting feature is still not working.Mystery
I have integrated solr with ajax-solr that helps in creating a UI. In ajax solr, Manager.response.highlighting reflects the highlighted content. I made the changes in solrconfig.xml as suggested by you however Manager.response.highlighting does not show any result. Can you please guide me on how do I enable this feature from scratch? Im using the default /search handler. Do i need to enable something there? ThanksMystery
P
4

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);

}));
Plasticizer answered 23/9, 2013 at 21:14 Comment(0)
S
0

Highlighting in SOLR is can be achieved by editing the solr.xml, and specifying the parameters there. You can check documentation here: http://wiki.apache.org/solr/HighlightingParameters

Specify answered 17/6, 2013 at 6:26 Comment(1)
I don't see any file named solr.xml. Should it be solrconfig.xml?Studnia

© 2022 - 2024 — McMap. All rights reserved.