drupalorg-1.0.x-dev/src/EventSubscriber/SearchApiSubscriber.php

src/EventSubscriber/SearchApiSubscriber.php
<?php

namespace Drupal\drupalorg\EventSubscriber;

use Drupal\search_api_opensearch\Event\QueryParamsEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Provides the SearchApiSubscriber class.
 */
class SearchApiSubscriber implements EventSubscriberInterface {

  /**
   * Alters the params for the Open Search query.
   *
   * @param \Drupal\search_api_opensearch\Event\QueryParamsEvent $event
   *   The query params event object.
   *
   * @see https://opensearch.org/docs/latest/query-dsl/compound/function-score/
   * @see https://opensearch.org/docs/latest/query-dsl/query-filter-context/
   * @see https://drupalorg.ddev.site:5602/app/dev_tools#/console
   */
  public function openSearchQueryTotalInstalls(QueryParamsEvent $event) {
    $sorts = $event->getQuery()->getSorts();
    if (empty($sorts)) {
      $params = $event->getParams();
      $original_query = $params['body']['query'] ?? FALSE;
      if (!empty($original_query['bool']) && empty($original_query['bool']['must']['query_string'])) {
        // If no fulltext query is made, set up an always-true query so the
        // scoring function runs, as otherwise it will just filter and not
        // score the results.
        $original_query['bool']['must']['query_string'] = [
          'query' => '_exists_: title',
        ];
      }
      $new_query = [
        'function_score' => [
          'field_value_factor' => [
            'field' => 'active_installs_total',
            'factor' => 1.5,
            'modifier' => 'log1p',
            'missing' => 1,
          ],
        ],
      ];
      if ($original_query) {
        $new_query['function_score']['query'] = $original_query;
      }

      $params['body']['query'] = $new_query;
      $event->setParams($params);

      // Useful debug to see the query made and the results + score:
      // dump($params);
      // In `web/modules/contrib/search_api_opensearch/src/SearchAPI/BackendClient.php:173`
      // dd($response); // To check the score on successful responses.
      // Then in `web/modules/contrib/search_api_opensearch/src/SearchAPI/BackendClient.php:180`
      // dd($e); // To check what the error is if there is any.
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    return [
      QueryParamsEvent::class => 'openSearchQueryTotalInstalls',
    ];
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc