Skip to content

Instantly share code, notes, and snippets.

@prashantdsala
Created December 4, 2023 10:04
Show Gist options
  • Save prashantdsala/e96c9d8fdb698cfa075ae231ae8b4aa7 to your computer and use it in GitHub Desktop.
Save prashantdsala/e96c9d8fdb698cfa075ae231ae8b4aa7 to your computer and use it in GitHub Desktop.
Alter Apache Solr Query and Boost Results
services:
custom_search.event_subscriber:
class: Drupal\custom_search\EventSubscriber\CustomSearchSubscriber
tags:
- { name: event_subscriber }
<?php declare(strict_types = 1);
namespace Drupal\custom_search\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\search_api_solr\Event\PreQueryEvent;
use Drupal\search_api_solr\Event\SearchApiSolrEvents;
use Drupal\search_api\Query\QueryInterface as SapiQueryInterface;
use Solarium\Core\Query\QueryInterface as SolariumQueryInterface;
/**
* @todo Add description for this subscriber.
*/
final class CustomSearchSubscriber implements EventSubscriberInterface {
/**
* Kernel request event handler.
*/
public function onKernelRequest(RequestEvent $event): void {
// @todo Place your code here.
}
/**
* Kernel response event handler.
*/
public function onKernelResponse(ResponseEvent $event): void {
// @todo Place your code here.
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
return [
SearchApiSolrEvents::PRE_QUERY => 'preQuery',
];
}
/**
* {@inheritdoc}
*/
public function preQuery(PreQueryEvent $event): void {
$query = $event->getSearchApiQuery();
$solarium_query = $event->getSolariumQuery();
// change tm_X3b_en_title and ss_field_order field names as per you solr field names.
// Searching the text "testing" in tm_X3b_en_title field and boosting the ss_field_order field
// having the value as "first".
$solarium_query->addParam("q", "(tm_X3b_en_title:testing AND ss_field_order:first^5)");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment