* Scores keyed by nid, best first, none when materio_ai is switched off. * Solr score of a cosine kNN query: * (1 + cosine) / 2. * * @throws \Drupal\materio_ai\Exception\EmbeddingException * When the model fails or is too slow (QueryEmbedder). * @throws \Drupal\search_api\SearchApiException * When Solr fails. */ public function search(string $phrase, ?string $langcode = NULL, int $limit = 100): array { // Switched off: no text is sent to the model, keyword results only. if (!$this->embedder->isEnabled()) { return []; } return $this->searchVector($this->embedder->embed($phrase), $langcode, $limit); } /** * Nodes closest to a vector, best first (see search()). * * @param float[] $vector * Query vector, of the configured dimension. * * @return array * Scores keyed by nid, best first. */ public function searchVector(array $vector, ?string $langcode = NULL, int $limit = 100): array { $dimension = (int) $this->configFactory->get('materio_ai.settings')->get('dimension'); if (count($vector) !== $dimension || $limit <= 0) { return []; } $index = $this->entityTypeManager->getStorage('search_api_index')->load(self::INDEX); $query = $index->query(); $query->setLanguages([$langcode ?? $this->languageManager->getCurrentLanguage()->getId()]); $query->range(0, $limit); $query->sort('search_api_relevance', 'DESC'); $query->setOption(self::OPTION_VECTOR, array_values($vector)); // Only the item IDs are needed. $query->setOption('search_api_retrieved_field_values', ['search_api_id' => 'search_api_id']); $query->addTag(self::TAG); $scores = []; foreach ($query->execute() as $item_id => $item) { [, $raw_id] = Utility::splitCombinedId($item_id); $nid = (int) explode(':', $raw_id, 2)[0]; $scores[$nid] ??= (float) $item->getScore(); } return $scores; } }