Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 594
Archit Arora Avatar asked Jun 17 '13 06:06

Archit Arora


2 Answers

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

}));
like image 136
delkant Avatar answered Nov 15 '22 09:11

delkant


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>
like image 32
Jayendra Avatar answered Nov 15 '22 08:11

Jayendra