You are here

public static function Utility::flattenKeysToPayloadScore in Search API Solr 8.3

Same name and namespace in other branches
  1. 4.x src/Utility/Utility.php \Drupal\search_api_solr\Utility\Utility::flattenKeysToPayloadScore()

Flattens keys into payload_score queries.

Parameters

array|string $keys: The keys array to flatten, formatted as specified by \Drupal\search_api\Query\QueryInterface::getKeys() or a phrase string.

string $parse_mode_id: (optional) The parse mode ID. Defaults to "phrase".

Return value

string A Solr query string representing the same keys.

Throws

\Drupal\search_api_solr\SearchApiSolrException

1 call to Utility::flattenKeysToPayloadScore()
SearchApiSolrBackend::search in src/Plugin/search_api/backend/SearchApiSolrBackend.php
Options on $query prefixed by 'solr_param_' will be passed natively to Solr as query parameter without the prefix. For example you can set the "Minimum Should Match" parameter 'mm' to '75%' like this:

File

src/Utility/Utility.php, line 853

Class

Utility
Provides various helper functions for Solr backends.

Namespace

Drupal\search_api_solr\Utility

Code

public static function flattenKeysToPayloadScore($keys, string $parse_mode_id = 'phrase') : string {
  $k = [];
  $payload_scores = [];
  if (is_array($keys)) {
    $queryHelper = \Drupal::service('solarium.query_helper');
    $escaped = $keys['#escaped'] ?? FALSE;
    foreach ($keys as $key_nr => $key) {
      if (!$key || strpos($key_nr, '#') === 0) {
        continue;
      }
      if (is_array($key)) {
        if ($subkeys = self::flattenKeysToPayloadScore($key, $parse_mode_id)) {
          $payload_scores[] = $subkeys;
        }
      }
      elseif ($escaped) {
        $k[] = trim($key);
      }
      else {
        switch ($parse_mode_id) {
          case 'terms':
          case "sloppy_terms":
          case 'phrase':
          case "sloppy_phrase":
          case 'edismax':
            $k[] = $queryHelper
              ->escapePhrase(trim($key));
            break;
          default:
            throw new SearchApiSolrException('Incompatible parse mode.');
        }
      }
    }
  }
  elseif (is_string($keys)) {
    switch ($parse_mode_id) {
      case 'direct':

        // NOP.
        break;
      default:
        throw new SearchApiSolrException('Incompatible parse mode.');
    }
  }

  // See the boost_term_payload field type in schema.xml. If we send shorter
  // or larger keys then defined by solr.LengthFilterFactory we'll trigger a
  // "SpanQuery is null" exception.
  $k = array_filter($k, function ($v) {
    $v = trim($v, '"');
    return mb_strlen($v) >= 2 && mb_strlen($v) <= 100;
  });
  if ($k) {
    $payload_scores[] = ' {!payload_score f=boost_term v=' . implode(' func=max} {!payload_score f=boost_term v=', $k) . ' func=max}';
  }
  return implode('', $payload_scores);
}