Random results with Apache Solr and Drupal

The schema.xml that comes with the Drupal Apache Solr module doesn't define the random_* field compared to the default xml included in the apachesolr package. We needed that functionality for a project where we wanted to display 3 blocks which showed random results based on a couple of fields available in the node, in our case the author, title and a cck field. With 300k nodes, a random result was giving a nicer experience instead of seeing the same results coming back over and over. Adding random order is pretty easy in a few simple steps: http://lucene.apache.org/solr/api/org/apache/solr/schema/RandomSortField...

Implementing the tags from that manual did not have a lot of success, however, after some fiddling, following changes in the xml seem to do the trick. Feel free to add comments and suggestions.

   <!-- goes in types -->
    <fieldType name="rand" class="solr.RandomSortField" indexed="true" />

  <!-- goes in fields -->
   <dynamicField name="random*" type="rand" indexed="true" stored="true"/>

After indexing your nodes, try to run following query on your solr admin page:

http://localhost:port/solr/select?q=whatever&morekeyshere&sort=random_127789 desc

Our blocks are defined via hook_block which uses the apachesolr_search_execute() function to launch our query to the solr engine. With the hook_apachesolr_modify_query you can add a sort parameter and you'll get your random results.

<?php
function hook_apachesolr_modify_query(&$query, &$params, $caller) {
  if (
$caller == 'whatever') {
   
$seed = rand(1, 200);
   
$params['qt'] = 'standard';
   
$params['sort'] = 'random_'. $seed .' asc';
  }
}
?>

Comments

Submitted by Robert Douglass on December 20, 2009 - 12:59

As of RC4 there's a random field in the schema. It's not used anywhere in the module yet, but your techniques here can now be used without having to modify schema.xml.


<!-- A random sort field -->
<dynamicField name="random_*" type="rand" indexed="true" stored="true"/>

Submitted by riddhi on February 14, 2012 - 10:06

I want to get random result on the basis of CCK field i.e. On the basis of membership, there are 3 types and I want to get random and sorted result on membership. Pls confirm what steps we need to do for a particular cck field?

Submitted by Linda on December 28, 2013 - 03:44

I'm not quite sure if the above applies to my situation.

I would like to execute a search using the Apache Solr Search module that based on a randomly selected taxonomy term field.

I'm using Drupal 7 so assuming I should be using hook_apachesolr_query_alter.

Any input would be appreciated.

Thanks,
Linda

Submitted by swentel on December 28, 2013 - 12:40

That hook is the right one. You'll have to todo something like this

<?php
$query->addFilter('name_of_the_solr_key', $term_id);
?> 

You can find the names of those keys in the administration overview of solr itself.

You are here