blog-banner

Drupal 7 Filtering SOLR Results

  • APACHE SOLR
  • Drupal 7
  • Drupal Planet

Drupal Module Filter

Search plays a crucial role in content-driven websites. Drupal and the Open-source enterprise search platform Solr form an effective combination. Drupal 7 has an apachesolr module that integrates Drupal with the Apache Solr search platform. I am going to detail how to alter the solr query to get better and more precise results.

Use cases:

  1. You may limit the result set to specific content types
  2. Search only on specific fields
  3. Modify the field weightage
  4. Restrict results based on conditions
and so on.
 

Hook used:

 
We need to use hook_apachesolr_query_prepare($query) hook to add custom params.
 

Limiting results set:

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

function MODULE_search_apachesolr_query_prepare($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 to search only in the label field.
 
$query->addParam('qf','label content')
 
The above param makes solr to search only in label and content fields.
 
 
Field weightage
 
$query->addParam('qf','content^3 label^5')
 
the above code specifies field weightage. The meaning label has higher precedence than content. The label is the node title here.
 
Nesting Filters:
 
Let's assume you have a validity field, based on it, you want to receive only valid records leaving old dated records.
 

  $filter2 = new SolrFilterSubQuery('AND');

  $filter2->addFilter('bundle''student');

  $filter2->addFilter('dm_field_student_validity','[NOW TO *]');

It receives the students who have validity date not lesser than current date. You can nest multiple filters,

function MODULE_apachesolr_query_prepare($query) {

  $filter = new SolrFilterSubQuery('AND');

  $filter->addFilter('bundle''student');

  $filter->addFilter('dm_field_student_validity','[NOW TO *]');

  $compiled_filter = new SolrFilterSubQuery('OR');

  $compiled_filter->addFilter('bundle''teacher');

  $compiled_filter->addFilterSubQuery($filter);

  //finally add the compiled filter to main query object

  $query->addFilterSubQuery($compiled_filter);

}

 

Get awesome tech content in your inbox