SolrConfigSubscriber listens to PostConfigFilesGenerationEvent (search_api_solr 4.x no longer calls hook_search_api_solr_config_files_alter) and appends the knn_vector_1024 DenseVectorField (cosine, HNSW) and the knn1024_* dynamic field (not stored). Solr 9.1 at least. Dependency on search_api_solr added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ShDspHaZGwHoRZCsPBJzsM
60 lines
1.8 KiB
PHP
60 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Drupal\materio_ai\EventSubscriber;
|
|
|
|
use Drupal\Core\Config\ConfigFactoryInterface;
|
|
use Drupal\materio_ai\Solr\VectorField;
|
|
use Drupal\search_api_solr\Event\PostConfigFilesGenerationEvent;
|
|
use Drupal\search_api_solr\Event\SearchApiSolrEvents;
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
|
|
|
/**
|
|
* Adds the dense vector field to the generated Solr configset.
|
|
*
|
|
* Event of search_api_solr 4.x, which replaces
|
|
* hook_search_api_solr_config_files_alter(). Solr 9.1 at least: pre-filters
|
|
* (fq) apply to the kNN search only from this version.
|
|
*/
|
|
final class SolrConfigSubscriber implements EventSubscriberInterface {
|
|
|
|
public function __construct(
|
|
private readonly ConfigFactoryInterface $configFactory,
|
|
) {}
|
|
|
|
/**
|
|
* {@inheritdoc}
|
|
*/
|
|
public static function getSubscribedEvents(): array {
|
|
if (!class_exists(SearchApiSolrEvents::class)) {
|
|
return [];
|
|
}
|
|
return [SearchApiSolrEvents::POST_CONFIG_FILES_GENERATION => 'addVectorField'];
|
|
}
|
|
|
|
/**
|
|
* Appends the field type and the dynamic field to the schema_extra files.
|
|
*/
|
|
public function addVectorField(PostConfigFilesGenerationEvent $event): void {
|
|
if (version_compare($event->getLuceneMatchVersion(), '9.1', '<')) {
|
|
return;
|
|
}
|
|
$dimension = (int) $this->configFactory->get('materio_ai.settings')->get('dimension');
|
|
if ($dimension <= 0) {
|
|
return;
|
|
}
|
|
$files = $event->getConfigFiles();
|
|
foreach ([
|
|
'schema_extra_types.xml' => VectorField::typeXml($dimension),
|
|
'schema_extra_fields.xml' => VectorField::dynamicFieldXml($dimension),
|
|
] as $file => $xml) {
|
|
if (isset($files[$file]) && !str_contains($files[$file], $xml)) {
|
|
$files[$file] .= $xml;
|
|
}
|
|
}
|
|
$event->setConfigFiles($files);
|
|
}
|
|
|
|
}
|