Add hook_ai_search_results_alter() to allow other modules to modify or re-rank AI search results

Created on 4 November 2025, 11 days ago

Currently, the AI Search processor in the ai_search module executes the search query and returns scored entity results directly.
There is no way for other modules to adjust or re-rank these results before they are returned.

This issue introduces a new hook:

hook_ai_search_results_alter(array &$results, $keywords)

Purpose

The new hook allows other modules to:

  • Adjust or boost relevance scores for specific entities (e.g., promote certain content types).
  • Filter or remove results.
  • Reorder results based on custom business logic.

Example Implementation

function mymodule_ai_search_results_alter(array &$results, $keywords): void {
  // Example: Boost a specific node manually.
  if (isset($results['entity:node/8215:en'])) {
    $results['entity:node/8215:en'] += 0.2;
  }

  // Example: Slightly boost all "article" nodes.
  foreach ($results as $entity_id => $score) {
    if (preg_match('/^entity:node\/(\d+)/', $entity_id, $matches)) {
      $nid = (int) $matches[1];
      $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
      if ($node && $node->bundle() === 'article') {
        $results[$entity_id] = $score + 0.05;
      }
    }
  }

  arsort($results);
}

Developer Notes

  • The hook is invoked in the AiSearchProcessor::getAiSearchResults() method right before returning the $ai_entity_ids.
  • It follows Drupal’s standard alter pattern.
  • Example usage is documented in ai_search.api.php.

Benefits

  • Extensibility: enables contrib and custom modules to influence AI ranking logic.
  • Better integration with site-specific or domain-specific relevance tuning.
  • Non-breaking change: existing functionality remains unaffected unless the hook is implemented.
Feature request
Status

Active

Version

1.2

Component

AI Search

Created by

🇺🇦Ukraine nnevill Lutsk

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

No activities found.

Production build 0.71.5 2024