Skip to content

Instantly share code, notes, and snippets.

@juampynr
Last active September 22, 2015 18:02
Show Gist options
  • Save juampynr/96dd6f963defcfef1410 to your computer and use it in GitHub Desktop.
Save juampynr/96dd6f963defcfef1410 to your computer and use it in GitHub Desktop.
Drupal query template for Apache Solr

The following is a template for you to write custom queries against Apache Solr. It is documented in a way that resembles as much as possible how to write a SQL query.

Once you have set up Apache Solr Search module and connected a Solr server to Drupal, you can download the following file to the root of your Drupal site, adjust the query, and execute it with the following Drush command:

drush scr custom_solr_query.php
<?php
/**
* @file
*
* Sample query using Drupal's Apache Solr Search module's API.
*
* Read each of the sections and adjust it to your needs.
*/
try {
// The following loads the Apache Solr Query object.
// The query object and its result will be saved statically during the request
// by the name given in the first argument so if you are going to make more
// than one query in the same request, change the name parameter.
$query = apachesolr_drupal_query('my_custom_query');
// 1. SELECT: we choose which fields we want per result by setting the `fl` (field list) parameter.
// This is like writing `SELECT title, body` in an SQL query.
$query->addParam('fl', 'entity_id,label,sm_field_image');
// 2. FROM: There is no FROM mapping in Solr nor INNER JOIN as it simply stores documents whose
// data structure may be different. Therefore, we need to use filters to select which
// documents we want. We will do this in the next section.
// 3. WHERE: This is the trickiest bit of writing Solr queries, specialy if we want to
// nest conditions such as AND (title = 'lullabot' OR created > 1442943481).
// 4. SORT BY::
// 5. LIMIT:
}
catch (Exception $e) {
watchdog('bgpage', 'Could not connect to Solr to fetch data. Error was %error.', array(
'%error' => $e->getMessage(),
), WATCHDOG_ERROR);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment