Programmatically update Search API index

Programmatically update Search API index

Let's say that you use the Search API module and that you have SOLR and Database servers. One search index can use only one server at the time, so if something goes wrong with one of the servers and you have to switch to another server how would you do it if you had to write an update hook?

Both Server and Index are Config entities defined in the Search API module. You can see that here:

So, if we have a server called 'database_server' and index called 'search_index' we can use the following code to change the server:

use Drupal\search_api\Entity\Index;
use Drupal\search_api\Entity\Server;

 * Change search server to Database server.
function MY_MODULE_update_8001() {
  $server = Server::load('database_server');
  $index = Index::load('search_index');

Make sure that your server is enabled before you attempt to switch to it. You can programmatically enable a server by adding this line:


In some cases when we have simpler Config entities (like Block) that don't have much going on in their preSave() and postSave() methods, we can use the ConfigFactory to load a config item and set a new value. preSave() method in the Block class is only checking if the region is valid, and postSave() method is invalidating cache tags.

For example, to display a block title we could do this:

$block_config = \Drupal::configFactory()>getEditable('block.block.bartik_page_title');
$block_config->set('settings.label_display', 'visible');

But, using the ConfigFactory is not possible here, because the Index entity has a lot of interesting stuff in the preSave() and postSave() methods. We have to load the entity and then use appropriate methods.

If I can be of assistance, please do not hesitate to contact me.

About the author

Goran Nikolovski is a highly experienced Drupal developer with an extensive skill set that includes PHP, MySQL, HTML, CSS and Javascript. He has experience with large Drupal sites and Drupal Commerce 2.x integration, and he is author of several Drupal modules.

You may also like

An alternative to Menu Token module

As of writing this blog post, the Menu Token module for Drupal 8 is still in the alpha version and it might not work in all cases. That's why having an alternative solution is great. The alternative to using the Menu Token module for Drupal 8 is to use Menu link plugins.