Performing Ranged Solr Searches Against CCK Fields

I just recently encountered a use case where I needed to perform ranged searches in Drupal against a Solr back-end. This ended up being far easier than I ever anticipated. Here's a quick walkthrough of the steps involved to expose a CCK field to Solr and then explicitly use it when conducting searches. This was done using a Solr 1.4 engine and http://drupal.org/project/apachesolr 6.x-1.0-rc5

This took me a while to figure out and ended up being quite simple once complete ... I hope it saves someone the headache I got from trying to figure it out! So here we go ... in 3 simple steps.

Use Case: provide the ability to perform a ranged search against a boat content type. Or, to state it another way, the ability to return all boats between X and Y feet.

Step 1: Modify the content type to add a CCK field named field_boat_length of type integer and create relevant content.

Step 2: Use the dynamic fields in Solr to index field_boat_length for use in ranged queries. This is done by implementing apachesolr_cck_fields_alter(). The only thing we need to do is register field_boat_length as needing per-field mappings and identify the data type we are using.

function boat_apachesolr_cck_fields_alter(&$mappings) {
  $mappings['per-field']['field_boat_length'] = array(
    'callback' => '',
    'index_type' => 'integer'
  );
}

Step 3: Pass the proper filter string to apachesolr_search_execute(). All filters that get passed to Solr are passed as a simple text string. Here's a couple of quick examples that will illustrate the syntax better than my explanations:

  • boats between 25 and 45 feet is_cck_field_boat_length:[25 TO 45]
  • boats greater than 45 feet is_cck_field_boat_length:[45 TO *]

The is_cck part of the filter names that are you passing in stand for integer sortable cck and are automatically generated by the solr module when creating the dynamic fields. Ultimately these filter strings get passed into apachesolr_search_execute() as the $filter argument.

Yep ... it really is that easy.