How To Create Custom SOLR Search With Autocomplete In Drupal 7
Blog

How To Create Custom SOLR Search With Autocomplete In Drupal 7

In many cases, users visiting a site already know what they are looking for, hence they  head straight to the search box. Since it is likely to be their first point of contact with the website, retailers must ensure that they get it right the first time. This is to avoid the issue of users getting frustrated by inaccurate or badly-ranked results and as a result moving on to a different site.

A good starting point is to introduce a ‘suggest’(Autocomplete) function, which lists a drop-down menu of various  search queries containing the text fragment they have typed.

We will integrate the apache solr with our drupal site and make autocomplete search.
For this, we need to query the apache solr and then get the results from the apache finally  displaying it in autocomplete. With this we can customize our autocomplete search result.

Modules Required

  • Apache solr search
  • Apache solr Autocomplete

To Install and configure apache solr with drupal 7 please follow this

http://valuebound.com/resources/blog/installing-configuring-apache-solr-520-with-drupal-7-using-search-api-ubuntu-1404
 

Step 1:
Create the block to place search text field

/**
 * Implements hook_block_info().
 */
function solr_search_block_info() {
  $blocks = array();
  $blocks['solr_search_block'] = array(
    'info' => t('Place the Solr Search Block in any region'),
  );
 
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function solr_search_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'solr_search_block':
      $block['subject'] = '';
      $block['content'] = drupal_get_form('solr_search_block_form');
      break;
  }
  return $block;
}

Step 2:
Create the custom form with text field and make the text field autocomplete. Then place the following form in the block

 function solr_search_block_form($form, &$form_state) {
$form[‘search’] = array(
        '#type' => 'textfield',
        '#id' => 'edit-custom-search-block-id',
        '#autocomplete_path' => 'solr-search/autocomplete',
        '#attributes' => array('placeholder' => t('Search any thing'), 'class' => array("edit-custom-search-block"))
      );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Search',
  );
return $form;
}


/*
 * Implementing hook_menu()
 */
function solr_search_menu() {
  $items = array();

  $items['solr-search/autocomplete'] = array(
    'page callback' => 'search_autocomplete',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );
  return $items;
}

Step 3:

Let’s look at the callback function of the hook_menu which returns the autocomplete result.

function search_autocomplete($keyword = '') {
  global $base_url;
 
  $search_spell = _get_search_label_spellcheck($keyword);

  if (isset($search_spell) && !empty($search_spell)) {
    //$search_spell_link = l(t($search_spell), $base_url.'/search/site/'.$search_spell);
    $search_spell_link = l(t($search_spell), $base_url . '/search/site/' . $search_spell, array('attributes' => array('class' => array('search-custom-spellcheck')), 'html' => TRUE));
  }

  /**
 * Helper function that suggests ways to complete partial words.
 *
 * For example, if $keys = "learn", this might return suggestions like:
 *    learn, learning, learner, learnability.
 * The suggested terms are returned in order of frequency (most frequent first).
 *
   */


  $suggestions = array();
  $suggestions = array_merge($suggestions, apachesolr_autocomplete_suggest_word_completion($keyword, 5));
  if (apachesolr_autocomplete_variable_get_suggest_keywords() || apachesolr_autocomplete_variable_get_suggest_spellcheck()) {
    $suggestions = array_merge($suggestions, apachesolr_autocomplete_suggest_additional_term($keyword, 5));
  }
  if ($suggestions) {
    foreach ($suggestions as $key => $suggestion) {
      $spell = substr($key, 1);
      $search = _get_search_complete_keywords($spell);
      if (!empty($search)) {
        foreach ($search->response->docs as $sugg) {
          $node_id = $sugg->entity_id;
            if (!empty($node_id)) {
              $node_detail = node_load($node_id);
              $title = $node_detail->title;
              $matches[$title] = _get_search_autocomplete_list_display($sugg, $title);
            }
        }
      }
    }
  }

  if (!empty($matches)) {
    $url = $_GET['q'];
    $url_explode = explode('/', $url);
    $url_last = end($url_explode);
    //    $matches['more'] = l('VIEW ALL PRODUCTS', "$base_url/search/site/$url_last", array('attributes' => array('class' => array('search-more-autocomplete'))));
  }
  else {
    if (!empty($search_spell_link)) {
      $spellcheck_html = '

Finding for"' . $search_spell_link . '"?
';
      $matches[$keyword] = $spellcheck_html;
    }
    $matches[""] = "NO RESULT FOUND";
  }
  drupal_json_output($matches);
}


function _get_search_label_spellcheck($keys) {
  if ($keys) {
    $keys = preg_replace('/[^A-Za-z\-]/', '', $keys);
// Ask Solr to return facets from the 'spell' field to use as suggestions.
    $params = apachesolr_autocomplete_basic_params($suggestions_to_return);
    if (!empty($keys)) {
 //Helper function to get suggestions from Solr.
      $result = apachesolr_autocomplete_suggest($keys, $params, $keys);
    }
    if (!empty($result) && isset($result['response']->spellcheck)) {
      foreach ($result['response']->spellcheck->suggestions as $key => $check) {
        $spell[$key] = $check->suggestion[0];
      }
    };
    return $spell[$key];
  }
}

Step 4:
Next, we need to query the apache solr based on the text entered in the text field. This  will return the result from the solr.

function _get_search_complete_keywords($keyword) {
  if (!empty($keyword)) {
    $solr = apachesolr_get_solr();
    $query = apachesolr_drupal_query("custom", array('q' => $keyword));
    $query->addParam('rows', '1000'); // How many rows of result to display default it is 10.
    $query->addParam('qf', 'label'); // Only search in title
    //The bundle which you want to search
    $query->addFilter("bundle", "article");
    $query->setSolrsort('sort_label', 'asc');
    $resp_search = $query->search();
    return $resp_search;
  }
}

Step 5:
To display the autocomplete results in the textbox enter the following code:

function _get_search_autocomplete_list_display($sugg, $title) {
  global $base_url;
  if (!empty($sugg)) {
    $nid = $sugg->entity_id;
  }
  $n_link = $base_url . '/node/' . $nid;
  $title_link = l(t($title), $n_link, array('attributes' => array('class' => array('search-title-autocomplete'), 'title' => $title)));
  $data = '

' . $title_link .
      '
';

  return $data;
}

There you go! Now with autocomplete search allowing you the opportunity to tweak your content which is present in the article content type more users will find the information they need on your site.

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch