You are here

protected function SearchBuilder::getSortSearchQuery in Elasticsearch Connector 8.7

Same name and namespace in other branches
  1. 8.2 src/ElasticSearch/Parameters/Builder/SearchBuilder.php \Drupal\elasticsearch_connector\ElasticSearch\Parameters\Builder\SearchBuilder::getSortSearchQuery()
  2. 8.5 src/ElasticSearch/Parameters/Builder/SearchBuilder.php \Drupal\elasticsearch_connector\ElasticSearch\Parameters\Builder\SearchBuilder::getSortSearchQuery()
  3. 8.6 src/ElasticSearch/Parameters/Builder/SearchBuilder.php \Drupal\elasticsearch_connector\ElasticSearch\Parameters\Builder\SearchBuilder::getSortSearchQuery()

Helper function that returns sort for query in search.

Return value

array Sort portion of the query.

Throws

\Exception

1 call to SearchBuilder::getSortSearchQuery()
SearchBuilder::getSearchQueryOptions in src/ElasticSearch/Parameters/Builder/SearchBuilder.php
Helper function to return associative array with query options.

File

src/ElasticSearch/Parameters/Builder/SearchBuilder.php, line 338

Class

SearchBuilder
Class SearchBuilder.

Namespace

Drupal\elasticsearch_connector\ElasticSearch\Parameters\Builder

Code

protected function getSortSearchQuery() {
  $index_fields = $this->index
    ->getFields();
  $sort = [];
  $query_full_text_fields = $this->index
    ->getFulltextFields();
  foreach ($this->query
    ->getSorts() as $field_id => $direction) {
    $direction = mb_strtolower($direction);
    if ($field_id === 'search_api_relevance') {

      // Apply only on fulltext search.
      $keys = $this->query
        ->getKeys();
      if (!empty($keys)) {
        $sort['_score'] = $direction;
      }
    }
    elseif ($field_id === 'search_api_id') {
      $sort['id'] = $direction;
    }
    elseif (isset($index_fields[$field_id])) {
      if (in_array($field_id, $query_full_text_fields)) {

        // Set the field that has not been analyzed for sorting.
        $sort[$field_id . '.keyword'] = $direction;
      }
      else {
        $sort[$field_id] = $direction;
      }
    }
    else {

      // TODO: no silly exceptions...
      throw new \Exception(t('Incorrect sorting!'));
    }
  }
  return $sort;
}