kevinquillen
6/4/2014 - 7:06 PM

SOLR Views Code

SOLR Views Code

<?php
/**
 * Implements hook_views_query_alter().
 *
 * Integrates solr index search facets with select displays of the vr search
 * views in order to allow views built on normal views base tables (not search API)
 * to interact with SOLR for facet generation.  This is perhaps not the most
 * efficient approach, but provides a solution allowing the full extent of
 * normal views base table fields, filters and sorts to be used in conjunction
 * with SOLR facets.
 */
function vrweb_vr_views_query_alter(&$view, &$query) {
  if ($view->name === 'vacation_rental_listings') {
    // @TOO Add other eventual vacation-rental filter alteration stuff here.

    // Search API glue code for these displays.
    $vr_displays = array(
      'page_teasers',
      'page_map',
      'mre_map',
      'listings_by_amenity',
      'page_oceanfront',
      'page_pet_friendly',
    );

    // Go!
    if (in_array($view->current_display, $vr_displays)) {
      $query->build($view);
      // Something's up with pagers here, lets make sure we're always grabbing
      // all results.
      $query->limit = 0;
      $query->offset = 0;
      $view_results = $query->query()->execute()->fetchAll();

      // Use tags as a way to pass information between right now and when our
      // AJAX response is inspecting the request.
      $tags = array(
        "view_name:{$view->name}",
        "view_display:{$view->current_display}",
      );

      $solr_query = search_api_query('vacation_rentals');
      $filter = $solr_query->createFilter('OR', $tags);
      $base_field = $query->base_field;

      // Loop the initial views search results and create a list of nids.
      if (count($view_results) > 0 ) {
        foreach ($view_results as $vr) {
          $filter->condition($base_field, $vr->$base_field);
        }

        // Pass the filter to the solr search to further filter on facets.
        $solr_query->filter($filter);
        $solr_results = $solr_query->execute();

        if ($solr_results['result count']) {
          $entity_ids = array_keys($solr_results['results']);
          $alias = $query->ensure_table('rc_core_item');
          $query->add_where('', "$alias.eid", $entity_ids, "IN");
        }
        else {
          $query->add_where_expression('', 'FALSE = TRUE');
        }
      }
    }
  }
}
?>