Skip to content

Instantly share code, notes, and snippets.

@oksana-c
Last active November 10, 2018 12:48
Show Gist options
  • Save oksana-c/54f39cd75c4bce6b802dab963ebe0e2c to your computer and use it in GitHub Desktop.
Save oksana-c/54f39cd75c4bce6b802dab963ebe0e2c to your computer and use it in GitHub Desktop.
Search API Solr - hook_search_api_solr_converted_query_alter()
<?php
/**
* Implements hook_search_api_solr_converted_query_alter().
*
* Modifies Solarium query to group results by field.
* Modifies Solarium query to sort results by first geofield value within the multivalue field.
*/
function MODULE_search_api_solr_converted_query_alter(\Solarium\Core\Query\QueryInterface $solarium_query, \Drupal\search_api\Query\QueryInterface $query) {
// Alter the Solarium query.
// Get private property searchId in order to determine origin of the search query.
// This could probably be done better.
$ref_object = new \ReflectionObject($query);
$ref_property = $ref_object->getProperty('searchId');
$ref_property->setAccessible(TRUE);
$search_id = $ref_property->getValue($query);
if ($search_id === 'search_api_autocomplete:search') {
// Group results by indexed field.
// Use grouping only for the autocomplete search field query.
$solarium_query->addParam('group', TRUE);
$solarium_query->addParam('group.field', 'ss_type');
$solarium_query->addParam('group.limit', 5);
$solarium_query->addParam('group.format', 'grouped');
// Add grouping to the query options so the module knows to group the
// results.
$grouping = [
'use_grouping' => TRUE,
'group_sort' => ['ss_type' => $query::SORT_DESC],
'fields' => ['type'],
'group.format' => 'grouped',
];
// Set the grouping param.
$query->setOption('search_api_grouping', $grouping);
}
if ($search_id === 'views_page:provider_search__result_provider') {
// Sort providers by the first value in Locations field.
$options = $query->getOptions();
if (isset($options['search_api_location'])) {
$lat = $options['search_api_location'][0]['lat'];
$lon = $options['search_api_location'][0]['lon'];
$solarium_query->addParam('fq', '{!geofilt}');
// Use locs_ field (single indexed value) for the query and not locm_ (multivalue)
$solarium_query->addParam('sfield', 'locs_field_rh_location_geofield');
$solarium_query->addParam('pt', $lat . ',' . $lon);
$solarium_query->addParam('sort', 'geodist() asc');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment