[Drupal] How to add a custom field to an entity's search index in Drupal 7

| | 1 min read

If you want to display some custom text related to an entity (which are not part of the entities fields. Eg. Calculated sum based on some values of the fields) in your apache solr search result, you can do it in two simple steps.

  1. Implement hook_apachesolr_index_document_build().

    Using this hook, we can add any number of custom fields to the document that is going to be indexed.

  2. Implement hook_apachesolr_query_alter().

    We can alter the apache solr query here to add our custom fields to the query, so that we can get the value of our custom fileds in the search result.


   /**
     * Implements hook_apachesolr_index_document_build().
     */
    function mymodule_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {
      if ($entity_type == 'node') {
        if ($entity->type == 'myentity') {
          $document->addField('ss_event_link', 'node/' . $entity->nid);
        }
      }
    }  

    /**
     * Implements hook_apachesolr_query_alter().
     */
    function mymodule_apachesolr_query_alter($query) {
      $query->addParam('fl', 'ss_event_link');
    }
  

With this you can get the fields you added to the index in the search template files or in the search result preprocess hooks - hook_preprocess_search_results or hook_preprocess_search_result. The field can be accessed from $variables['result']['fields']['field_name']. In search_results, the $variables['results'] will be an array.