Adding filters from code Apache Solr - Drupal 7

04 Jan 2018
Solr in Drupal 7

Search plays a crucial role in content driven websites. Drupal 7 has the apachesolr module which integrates Drupal with the Apache Solr search platform. I am going to detail on how to alter the Solr query to get better and precise results. Hook used for filtering search result dynamically is:

hook_apachesolr_query_alter()

Solr in Drupal 7

Filtering Solr Result

Let's write a simple query, to limit results to two content types.

function hook_apachesolr_query_alter(DrupalSolrQueryInterface &$query) {
   $compiled_filter = new SolrFilterSubQuery('OR');
   $compiled_filter->addFilter('bundle', 'student');
   $compiled_filter->addFilter('bundle', 'teacher');
   $query->addFilterSubQuery($compiled_filter);
}

Searching specific fields

To search only on specific fields,

$query->addParam('qf','label')

The above param makes Solr search only in label field. 

$query->addParam('qf','label content')

The above param makes Solr search only in label and content fields.

Field weight

$query->addParam('qf','content^3 label^5')

the above code specifies field weight. Field "label" has higher precedence than content. Label is the node title here.

You can use these things for filtering results dynamically for several scenarios like filtering results based on specific taxonomy terms used in content.