Apachesolr, Drupal, Php

Drupal 7 Apache solr add custom sort to solr query parameter

Drupal 7 Apache solr add custom field to solr search index was my last post where i described how to add custom field to solr search index. Here i am going to describe how to add custom sort to solr query parameter so that you get result sorted with that field.

To modify the query parameter there is a hook provided by Apache solr search integration module hook_apachesolr_query_prepare() this hook is similar to hook_apachesolr_query_alter() but it is called before this hook.

You can apply sort on the basis of any single value field in apache solr search index like score, create date, update data, sticky etc. Before applying sort you have to make that available as sort field by calling the method setAvailableSort of DrupalSolrQueryInterface and then calling setSolrSort method you can set ascending or descending sort on that field. As here i am going to apply sort based on score field.

<?php
function apache_solr_search_facet_block_apachesolr_query_prepare(&amp;$query){
  $query->setAvailableSort('score', array('title' => t('Most Relevant'), 'default' => 'asc'));
  $query->setSolrSort('score', 'desc');
}
?>

You can also remove the existing sort field with removeAvailableSort method.

For drupal 6 these method were named as set_available_sort() and set_solr_sort(). See the following post  for more detail:

http://drupal.org/node/715276

Standard

One thought on “Drupal 7 Apache solr add custom sort to solr query parameter

  1. Mansur Ali says:

    Hi,
    How we can add functionality like Relevancy, Title, Type, Author and Date? I mean display a toggle link in “Sort by” block.

    Your help would be greatly appreciated thank you in advance.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s