5

Is it possible to programmatically execute a node search? Maybe via NodeSearch or Drupal\search?

The closest I could get was to programmatically do stuff such as:

\Drupal::service('search.index')->clear();

echo \Drupal::service('plugin.manager.search')->getCacheMaxAge();

Note that I don't want to use search_api but simply what Drupal 8 provides out of the box as a response to /search/node?keys=test. Also note that I don't wish to integrate via HTTP.

4
  • What do you want to use the results for?
    – user72672
    Jan 10, 2020 at 9:31
  • @Jdrupal get the nids which match and return them on a custom JSON api response.
    – cherouvim
    Jan 10, 2020 at 9:43
  • Can't you just make an entity query?
    – user72672
    Jan 10, 2020 at 9:44
  • @Jdrupal yes of course, but that would need a lot of code. I would also like to have the exact search result characteristics of Drupal search.
    – cherouvim
    Jan 10, 2020 at 9:46

1 Answer 1

7

You can achieve that with the search plugin used by the search page entity with the node_search id.

use Drupal\search\Entity\SearchPage;

// Default is the node_search page.
$id = \Drupal::service('search.search_page_repository')->getDefaultSearchPage();
$defaultSearchPage = SearchPage::load($id);
$searchPlugin = $defaultSearchPage->getPlugin();
$searchPlugin->setSearch($keywords, $parameters, $arguments);
$searchPlugin->buildResults(); // $searchPlugin->execute() works too if you want raw results
1
  • +1 for the answer. It took me time to figure out what data to use for $parameters and $arguments. Eventually got it working by using request class. i.e $searchPlugin->setSearch($keywords, \Drupal::request()->query->all(), \Drupal::request()->attributes->all()); Jan 24, 2020 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.