Adding Custom Fields to Apache Solr Search Results

As I mentioned in my previous post on adding a custom sort to Solr, this post is about something that is even simpler; adding a new field to the search results.  In our particular use case, we wanted to add a CCK image field to the results.  To add a slight twist, we needed to add a different image depending on the content type: the user picture for a profile node (created with content_profile module) or a CCK imagefield named field_main_image from the other content types.

To do this, we will use the two hooks used in the last example: hook_apachesolr_update_index() and hook_apachesolr_modify_query().  To start, we need to add the data to the Solr index.

/**
* Implementation of hook_apachesolr_update_index()
*/
function mymodule_apachesolr_update_index(&$document, $node) {
  // Index field_main_image as a separate field
  if ($node->type == 'profile') {
    $user = user_load(array('uid' => $node->uid));
    $document->setMultiValue('sm_field_main_image', $user->picture);
  }
  elseif (count($node->field_main_image)) {
    foreach ($node->field_main_image AS $image) {
      $document->setMultiValue('sm_field_main_image', $image['filepath']);
    }
  }
}

All we do is add the data to the index by adding it to the $doument object, which is passed by reference.  We are using the setMultiValue method since the imagefield can have multiple values, but if we were just adding one field, we would just use the addField method.  And, actually, according to the comments in the setMultiValue method, it is deprecated in favor of using addField, but this is working fine right now.  The field name is simply the 'sm_' dynamic field name pattern with field_main_image appended, since the field contains a string of the path to the image, and the sm_ field type represents a medium string (as defined in schema.xml).

Now that the data has been added to the index, we also need to add it to the query so it can be returned in the search results.  This is done amazingly easily:

function mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
  $params['fl'] .= ',sm_field_main_image';
}

Without going into too much detail on the format of $params, all you're doing is some basic PHP string concatenation and appending your newly indexed field to the fields to return array (['fl'])of the $params object.  For more information on $params, see the DCSF session video starting at 37:30.

And that's all there is to it; two very small hook implementations. Pretty easy, and pretty powerful.  Now that we have that down, we can do even more complex stuff.  My next post on Solr will be a slightly more involved example of creating a custom search path.

Share This