Customising Apache Solr Search Results

by Vincenzo Gambino

Whilst the default Drupal search is ample for most sites, we needed a search system that was faceted, wouldn’t bog down MySQL, and would work on a cluster.

One search solution that exceeded these requirements was Apache SOLR.

From the same people that brought you the ubiquitous HTTP server, SOLR is a java search engine that is hugely sophisticated, yet through the joys of Drupal modules, is really easy to set up. Simply grab this module, and follow this guide.

A bit more work is required to really replace the Drupal search. The Suppress Search module completely hides the drupal search, and redirects all searches via SOLR. How about reformatting the SOLR search results though? Using Drupal hooks, changing how the SOLR search results look is really easy.

There are two hooks of interest: hook_apachesolr_process_results() and hook_apachesolr_search_result_alter(). hook_apachesolr_process_results() is called for each item in the search result. It is passed an object containing the raw search result – the node title, search score (relevancy) etc. The node title displayed can be edited to include the relevancy score:

function apachesolr_custom_results_apachesolr_search_result_alter(&$arg) { 
   $show_score = variable_get "apachesolr_custom_results_showscore", 'hide');
  
   if($show_score == "show")
      { // append score to title
      $arg->title .= " [".$arg->score."]";
      } return $arg;
}

hook_apachesolr_search_result_alter(), on the other hand, is only called once. At this point the raw search result from SOLR has been converted to node objects, so all node details are available to tweak. In the code snippet below I’m hiding or showing the author’s avatar next to each result:

function apachesolr_custom_results_apachesolr_process_results(&$arg) {
// loop through each result, performing desired actions

   for($i = 0, $l = count($arg); $i < $l; $i++) {
   $show_author = variable_get("apachesolr_custom_results_hideauthor", 'def');
     
      if($show_author == 'hide')
      { // remove user
      $arg[$i]['user'] = "";
      }
      elseif ($show_author == 'pic') { // show user avatar
      $author = user_load($arg[$i]['node']->uid);
      if ($author->picture) {
      $arg[$i][’user’] = theme(’user_picture’, $author);
      }
      else
      { $arg[$i][’user’] = ‘Default User Picture‘;
      }
   }
}

To simplify deployment, I’ve made a module enabling some simple customization of the results. Whilst not that useful in itself, it would make a good starting point for further development. Apache Solr Customisation Framework Module Download. I have not put this on the Drupal.org Solr page yet since this is only a starting framework for a module.

BrightLemon