Drupal

Date-boosting Solr / Drupal search results

By replacing Drupal's core search with Solr, it's possible to gain very fine control of the results. Not only is Solr very flexble, but the apachesolr module is generous with its hooks. One potential use is boosting the score based on dates, so that recent documents receive a higher relevancy score. We've used this for the L.A. Philharmonic's ticket calendar to help patrons find upcoming events.


Filed under:

By replacing Drupal's core search with Solr, it's possible to gain very fine control of the results. Not only is Solr very flexble, but the apachesolr module is generous with its hooks. One potential use is boosting the score based on dates, so that recent documents receive a higher relevancy score. We've used this for the L.A. Philharmonic's ticket calendar to help patrons find upcoming events.

First, look up the name of the field you need in the schema browser (http://localhost:8983/solr/admin/ for a local install). You should be able to locate it based on the machine name of your Drupal field (assuming the index is up-to-date).

hook_apachesolr_query_alter()

Next, drop this hook in a custom module (note this is for Drupal 7). Substitute your field's name in for dm_field_date.

/**
 * Implements hook_apachesolr_query_alter().
 */
function hook_search_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  $query->addParam('bf', array('freshness' =>
    'recip(abs(ms(NOW/HOUR,dm_field_date)),3.16e-11,1,.1)'
  ));
}

Fine-tuning

This function will apply a +10 boost to a document with today's date, tapering off to about +1 after a year. To write your own boost function, consult the Solr Wiki page on FunctionQuery. Note there are no spaces in the function queries! Choosing the constants can feel a bit blind, so visualizing the function on Wolfram Alpha helps (the x-axis is in milliseconds):

Similar posts

Get notified on new marketing insights

Be the first to know about new B2B SaaS Marketing insights to build or refine your marketing function with the tools and knowledge of today’s industry.