You are here

public function SearchBuilder::build in Elasticsearch Connector 8.2

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

Return value

array

File

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

Class

SearchBuilder
Class SearchBuilder.

Namespace

Drupal\elasticsearch_connector\ElasticSearch\Parameters\Builder

Code

public function build() {

  // Query options.
  $params = IndexFactory::index($this->index, TRUE);
  $query_options = $this
    ->getSearchQueryOptions();

  // Main query.
  $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'] = [];
  $fields =& $body['fields'];

  // More Like This.
  if (!empty($query_options['mlt'])) {
    $mlt_query['more_like_this'] = [];
    $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'] = [];
    }
    $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'] = [];
  }

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