Files
materio-d9/web/modules/custom/materio_ai/src/EventSubscriber/KnnQuerySubscriber.php
T
bachirandClaude Opus 5.5 f1ebea91db materio_ai: neighbour search service with Solr kNN (I4)
NeighbourSearch::search() embeds a phrase and runs a Search API query on the
database index, tagged materio_ai_knn. KnnQuerySubscriber turns only this
query into {!knn f=knn1024_vector topK=N}: Search API filter queries
(content_access, language, index) stay as kNN pre-filters (Solr 9.1+), and
keyword queries are untouched. Sent in POST by http_method AUTO.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ShDspHaZGwHoRZCsPBJzsM
2026-11-17 10:51:32 +01:00

68 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Drupal\materio_ai\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\materio_ai\Search\NeighbourSearch;
use Drupal\materio_ai\Solr\VectorField;
use Drupal\search_api_solr\Event\PostConvertedQueryEvent;
use Drupal\search_api_solr\Event\SearchApiSolrEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Turns the tagged Search API query of NeighbourSearch into a {!knn} query.
*
* Any other query (keywords, autocomplete, views) is left untouched. The
* filter queries built by Search API (index, site, language, access) stay:
* Solr 9.1+ applies them as pre-filters of the kNN search. The vector makes
* the request ≈ 10 KB: with http_method AUTO, search_api_solr sends it in
* POST (Solarium postbigrequest), beyond the 8 KB GET limit of Jetty.
*/
final class KnnQuerySubscriber implements EventSubscriberInterface {
public function __construct(
private readonly ConfigFactoryInterface $configFactory,
) {}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
if (!class_exists(SearchApiSolrEvents::class)) {
return [];
}
return [SearchApiSolrEvents::POST_CONVERT_QUERY => 'toKnn'];
}
/**
* Replaces the main query by the kNN query.
*/
public function toKnn(PostConvertedQueryEvent $event): void {
$query = $event->getSearchApiQuery();
if (!$query->hasTag(NeighbourSearch::TAG)) {
return;
}
$vector = $query->getOption(NeighbourSearch::OPTION_VECTOR);
$dimension = (int) $this->configFactory->get('materio_ai.settings')->get('dimension');
if (!is_array($vector) || count($vector) !== $dimension) {
return;
}
$limit = $query->getOption('limit') ?: 100;
$solarium_query = $event->getSolariumQuery();
$solarium_query->setQuery(sprintf(
'{!knn f=%s topK=%d}[%s]',
VectorField::fieldName($dimension),
$limit,
implode(',', array_map(static fn ($v): string => sprintf('%.7g', $v), $vector)),
));
// No keyword parser on a kNN query.
foreach (['defType', 'qf', 'pf', 'mm', 'tie'] as $param) {
$solarium_query->removeParam($param);
}
}
}