Skip to main content
Start of main content.

Writing a custom Drupal Search API processor

by nick.schuch /

Share this post on social media

When working with the Search API Drupal module, sometimes we need to programmatically add information that is not available for indexing as a field. Lucky we can write our own custom pre-processor to provide this information to the index.

Overview

For our example scenario, we want to index nodes with an "Even" or "Odd" value based on the node ID. This will make this information available later on when we display the search results, such as in a facet or a field in the result.

Declaring the processor

First of all we need to delcare our custom preprocessor. This can be done with the following info hook in your *.module file.

/**
 * Implements hook_search_api_alter_callback_info().
 */
function search_api_divisible_search_search_api_alter_callback_info() {
  $callbacks = array();
  $callbacks['search_api_divisible_by_two'] = array(
    'name' => t('Divisible by two'),
    'description' => t('Flags the node as even or odd.'),
    'class' => 'SearchApiDivisibleByTwo',
  );
  return $callbacks;
}

Where the action happens

We need to make sure the class file is declared in the module's .info file. Here is an example.

files[] = includes/processor_divisible_by_two.inc

Now we can add the following to the file which contains the logic that will create the field for indexing.

/**
 * @file
 * Custom processor for handling grouping by even and odd.
 */

/**
 * Search API data alteration callback that checks divisble by two.
 */
class SearchApiDivisibleByTwo extends SearchApiAbstractAlterCallback {
  /**
   * Alter the items into there respective groups.
   */
  public function alterItems(array &$items) {
    foreach ($items as $item) {
      if (($item->nid % 2) == 0) {
        $item->divisible = t('Even');
      }
      else {
        $item->divisible = t('Odd');
      }
    }
  }

  /**
   * Processor details.
   */
  public function propertyInfo() {
    return array(
      'divisible' => array(
        'label' => t('Divisible by two'),
        'description' => t('If the node ID is divisble by two.'),
        'type' => 'string',
      ),
    );
  }
}

The Results

And here we go! We have a new processor ready to be enabled.

Processors are very powerful and can be a simple implementation that makes a huge difference when implementing complex search systems.

Sample code for this example can be found the here.