Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exclude paths from search index #576

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion config/sync/search_api.index.server_dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ dependencies:
module:
- node
- search_api
- server_search
id: server_dev
name: server_dev
description: ''
Expand Down Expand Up @@ -72,7 +73,7 @@ field_settings:
datasource_id: 'entity:node'
property_path: title
type: text
boost: !!float 3
boost: 3.0
dependencies:
module:
- node
Expand Down Expand Up @@ -114,6 +115,9 @@ processor_settings:
preprocess_query: -30
entity_status: { }
entity_type: { }
exclude_nodes_by_path_alias:
excluded_nodes:
- /search
language_with_fallback: { }
rendered_item: { }
tracker_settings:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Drupal\Tests\server_general\ExistingSite;

use Drupal\paragraphs\Entity\Paragraph;

/**
* A test case to test search integration.
*/
Expand Down Expand Up @@ -127,4 +129,94 @@ public function testFacetConfigSanity() {
$this->expectNotToPerformAssertions();
}

/**
* Checks if search page (LP with Search PT) isn't indexed.
*
* See "ExcludeNodeByPathAliasProcessor.php".
*/
public function testSearchPageNotIndexed(): void {
$paragraph = Paragraph::create([
'type' => 'search',
'field_title' => [
'value' => 'Search Test',
],
]);
$paragraph->save();
$this->markEntityForCleanup($paragraph);

$path_alias = '/search_6KmX9x99aG5o13xvqjkO868iR';
$title = 'Search_6KmX9x99aG5o13xvqjkO868iR';

// Create a search LP with a specific title and path.
$node = $this->createNode([
'title' => $title,
'langcode' => 'en',
'type' => 'news',
'status' => 1,
'field_paragraphs' => [
$paragraph,
],
'path' => [
'pathauto' => FALSE,
'alias' => $path_alias,
],
]);
$node->setPublished()->save();

// Trigger indexing.
$this->triggerPostRequestIndexing();

$this->waitForElasticSearchIndex(function () use ($node): void {
$this->drupalGet('/search', [
'query' => [
'key' => $node->label(),
],
]);
$session = $this->assertSession();
// Without search index processor this page should be in the results.
$session->elementTextContains('css', '.view-search', $node->label());
});

// Get the configuration factory service.
$config_factory = \Drupal::configFactory();

// Load the configuration of our "exclude_nodes_by_path_alias"
// search processor.
$config = $config_factory->getEditable('search_api.index.server_dev');

// Get the existing "excluded nodes" config array.
$excluded_nodes_original = $excluded_nodes_temporary = $config->get('processor_settings.exclude_nodes_by_path_alias.excluded_nodes');

if (!in_array($path_alias, $excluded_nodes_original)) {
// Add a new entry to the excluded nodes array.
$excluded_nodes_temporary[] = $path_alias;
// Set the updated excluded nodes array back to the configuration.
$config->set('processor_settings.exclude_nodes_by_path_alias.excluded_nodes', $excluded_nodes_temporary);

// Save the configuration.
$config->save();
}

// Save LP again so that cache gets cleared.
$node->save();

// Trigger indexing.
$this->triggerPostRequestIndexing();

// Wait for indexing to complete.
$this->waitForElasticSearchIndex(function () use ($node): void {
// First search using the exact long phrase.
$this->drupalGet('/search', [
'query' => [
'key' => $node->label(),
],
]);
$session = $this->assertSession();
$session->elementTextContains('css', '.view-empty', 'No results found');
});

// Restore original settings.
$config->set('processor_settings.exclude_nodes_by_path_alias.excluded_nodes', $excluded_nodes_original);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
<?php

namespace Drupal\server_search\Plugin\search_api\processor;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\node\NodeInterface;
use Drupal\path_alias\AliasManagerInterface;
use Drupal\search_api\Plugin\PluginFormTrait;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* Provides a processor to exclude specific nodes from being indexed.
*
* @SearchApiProcessor(
* id = "exclude_nodes_by_path_alias",
* label = @Translation("Exclude nodes by path alias"),
* description = @Translation("Exclude specific nodes from being indexed given path alias."),
* stages = {
* "alter_items" = 0,
* },
* locked = true,
* hidden = false,
* )
*/
class ExcludeNodeByPathAliasProcessor extends ProcessorPluginBase implements PluginFormInterface {

use PluginFormTrait;

/**
* The alias manager.
*
* @var \Drupal\path_alias\AliasManagerInterface
*/
protected AliasManagerInterface $aliasManager;

/**
* The core language manager service.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected LanguageManagerInterface $languageManager;

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
/** @var static $processor */
$processor = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$processor->aliasManager = $container->get('path_alias.manager');
$processor->languageManager = $container->get('language_manager');
return $processor;
}

/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'excluded_nodes' => [],
];
}

/**
* {@inheritdoc}
*/
public function alterIndexedItems(array &$items) {
$excluded_nodes_array = $this->getConfiguration()['excluded_nodes'];
if (empty($excluded_nodes_array)) {
return;
}

foreach ($items as $id => $item) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $object */
$object = $item->getOriginalObject()->getValue();

if (!$object instanceof NodeInterface || $object->bundle() !== 'landing_page') {
continue;
}

$languages = array_keys($this->languageManager->getLanguages());
foreach ($languages as $lang_id) {
// Get current node item path aliases for each language.
$path_alias = $this->aliasManager->getAliasByPath('/node/' . $object->id(), $lang_id);
// Check if the nodes' path alias is in the list of excluded aliases.
if (in_array($path_alias, $excluded_nodes_array)) {
unset($items[$id]);
}
}
}
}

/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$excluded_nodes = $this->getConfiguration()['excluded_nodes'];
$form['#description'] = $this->t('Excludes nodes from indexing given their path aliases.');

$form['excluded_nodes'] = [
'#type' => 'textarea',
'#title' => $this->t('Node path aliases to exclude'),
'#description' => $this->t('Enter the node path aliases to exclude from the search index one per line with leading slash (e.g. "/search" and not "search").'),
'#default_value' => $excluded_nodes ? implode("\n", $excluded_nodes) : '',
];

return $form;
}

/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$excluded_nodes = $form_state->getValue('excluded_nodes');

// Split the textarea value by newline.
$excluded_nodes_array = preg_split('/[\r\n]+/', $excluded_nodes);

// Remove empty values.
$excluded_nodes_array = array_filter($excluded_nodes_array);

// Save each line as a separate item in the configuration array.
$this->setConfiguration(['excluded_nodes' => $excluded_nodes_array]);
}

}