IDEAS | BLOG

Search Snippets with Search API and Display Suite

If you're using the Display Suite module -- and we here at Forum One are big fans -- you might have noticed an add-on to pull the search snippet from Apache Solr as a field you could add to a display mode. This means you can use Apache Solr to show parts of each piece of content that matches the search term and highlight it so the user has an idea of what they're going to get when the go to that page. You know, kind of like what Google does.

The only problem is that this only works with the actual Apache Solr module and not the Search API module. Thankfully with a small amount of code it's pretty easy to add that in as well. The first thing to do is configure the Search API Solr server to send the excerpt back so we can use that in our results. That's as easy as enabling a few checkboxes. Just navigate to the Search API configuration settings, click "Edit" next to the server and open up the "Advanced" fieldset.

search_api_advanced_settings Next we define a custom field through Display Suite through their hooks:

function my_module_ds_fields_info($entity_type) {
  $fields = array();

  if ($entity_type == 'node') {
    $fields['node']['solr_snippet'] = array(
      'title' => t('Solr snippet'),
      'field_type' => DS_FIELD_TYPE_FUNCTION,
      'function' => 'my_module_search_snippet',
      'ui_limit' => array('*|*'),
    );
  }

  if (isset($fields[$entity_type])) {
    return array($entity_type => $fields[$entity_type]);
  }

  return;
}

What this is going to do is create a new "field" that shows up when you go to configure a node's display mode called "Solr snippet." Now the next step is to actually get it working.

function my_module_search_snippet($field) {
  $excerpt = '';
  
  foreach (search_api_current_search() as $search) {
    list($query, $results) = $search;
  }

  if (TRUE === isset($results)) {
    $entity = $field['entity'];
    if (TRUE === isset($results['results'][$entity->nid]) && FALSE === empty($results['results'][$entity->nid]['excerpt'])) {
      $excerpt = theme('html_tag', array('element' => array('#tag' => 'p', '#value' => $results['results'][$entity->nid]['excerpt'])));
    }
  }
  
  return $excerpt;
}

What we're doing here is loading up all of the current Search API searches and grabbing the results from them. Search API Solr provides a value in the results called "excerpt" which contains the values populated by Apache Solr. We just wrap them in a paragraph tag and then call it a day. Now you can use that display mode where you are showing your search results, and give the user some contextual clues on what the content on the other end of the link is going to look like.