Restored guide

Geospatial Apache Solr searching in Drupal 6 by upgrading Solr to 3.1

May 18, 2011 · 2 min read · Eric London's Drupal Blog

Distance search needs a Solr that understands spatial fields. On the Drupal 6 Apache Solr setup this blog was using, that meant moving the Solr core forward to the 3.1 line and sending coordinates in the index.

What you are solving

A location stored on a node (latitude and longitude from the Location or a CCK pair) has to be indexed as a point Solr can filter and sort. Solr 1.4, bundled with earlier Apache Solr module releases, does not give you the spatial field types later schemas expect. Solr 3.1 does, which is why the upgrade is the whole story rather than a Drupal-only patch.

Upgrade the core, keep the schema deliberate

Take a copy of the Solr home directory first. Install Solr 3.1 beside the old core, copy the Drupal module's Solr 3 schema if the release provides one, and add a field for the point only after the core starts cleanly. Restart Solr, then load the admin ping page before you touch Drupal.

<field name="loc" type="location" indexed="true" stored="true"/>

The type name has to exist in that schema. Do not paste a field in until schema.xml defines it. A core that fails to load takes search down for the whole site.

Index and query from Drupal

When a node is indexed, write the coordinate in the form the field type expects, commonly a single string lat,lon. On the query side, add a spatial filter with a distance in kilometres and sort by distance only when the visitor actually passed a point. An empty origin should fall back to the normal keyword search.

function custom_apachesolr_update_index(&$document, $node) {
  if (!isset($node->field_lat[0]['value'], $node->field_lon[0]['value'])) {
    return;
  }
  $document->addField('loc', $node->field_lat[0]['value'] . ',' . $node->field_lon[0]['value']);
}

Hook names differ by Apache Solr module version. Implement the alter hook your installed module documents for index documents and for the query that is about to be sent.

Check before you deploy

  • Index one node with known coordinates and find it in Solr's query screen before you test through Drupal.
  • Search from a point near that node and from a point that should return nothing.
  • Keep the old core on disk until the new one has survived a full reindex.

Restored guide for the 18 May 2011 note on geospatial Solr search after moving to Solr 3.1.