You are here

protected function SearchApiElasticsearchBackend::buildSearchQuery in Elasticsearch Connector 8

Helper function build search query().

1 call to SearchApiElasticsearchBackend::buildSearchQuery()
SearchApiElasticsearchBackend::search in src/Plugin/search_api/backend/SearchApiElasticsearchBackend.php
Overrides search().

File

src/Plugin/search_api/backend/SearchApiElasticsearchBackend.php, line 1016
Contains the SearchApiElasticsearchBackend object.

Class

SearchApiElasticsearchBackend
Plugin annotation @SearchApiBackend( id = "elasticsearch", label = @Translation("Elasticsearch"), description = @Translation("Index items using an Elasticsearch server.") )

Namespace

Drupal\elasticsearch_connector\Plugin\search_api\backend

Code

protected function buildSearchQuery(QueryInterface $query) {

  // Query options.
  $query_options = $this
    ->getSearchQueryOptions($query);

  // Main query.
  $params = $query
    ->getOption('ElasticParams');
  $body =& $params['body'];

  // Set the size and from parameters.
  $body['from'] = $query_options['query_offset'];
  $body['size'] = $query_options['query_limit'];

  // Sort
  if (!empty($query_options['sort'])) {
    $body['sort'] = $query_options['sort'];
  }
  $body['fields'] = array();
  $fields =& $body['fields'];

  // More Like This
  if (!empty($query_options['mlt'])) {
    $mlt_query['more_like_this'] = array();
    $mlt_query['more_like_this']['like_text'] = $query_options['mlt']['id'];
    $mlt_query['more_like_this']['fields'] = array_values($query_options['mlt']['fields']);

    // TODO: Make this settings configurable in the view.
    $mlt_query['more_like_this']['max_query_terms'] = 1;
    $mlt_query['more_like_this']['min_doc_freq'] = 1;
    $mlt_query['more_like_this']['min_term_freq'] = 1;
    $fields += array_values($query_options['mlt']['fields']);
    $body['query'] = $mlt_query;
  }

  // Build the query.
  if (!empty($query_options['query_search_string']) && !empty($query_options['query_search_filter'])) {
    $body['query']['filtered']['query'] = $query_options['query_search_string'];
    $body['query']['filtered']['filter'] = $query_options['query_search_filter'];
  }
  elseif (!empty($query_options['query_search_string'])) {
    if (empty($body['query'])) {
      $body['query'] = array();
    }
    $body['query'] += $query_options['query_search_string'];
  }
  elseif (!empty($query_options['query_search_filter'])) {
    $body['filter'] = $query_options['query_search_filter'];
  }

  // TODO: Handle fields on filter query.
  if (empty($fields)) {
    unset($body['fields']);
  }
  if (empty($body['filter'])) {
    unset($body['filter']);
  }
  if (empty($query_body)) {
    $query_body['match_all'] = array();
  }

  // Preserve the options for futher manipulation if necessary.
  $query
    ->setOption('ElasticParams', $params);
  return $params;
}