Using Elasticsearch with Drupal 9.x

Requirements 

Add an Elasticsearch service 

1. Configure the service 

Use the elasticsearch type to define the service:

.platform/services.yaml
<SERVICE_NAME>:
    type: elasticsearch:<VERSION>
    disk: 256

2. Add the relationship 

Use the elasticsearch endpoint to define the relationship

.platform.app.yaml
relationships:
    <RELATIONSHIP_NAME>: "<SERVICE_NAME>:elasticsearch"

You can define <SERVICE_NAME> and <RELATIONSHIP_NAME> as you like, but it’s best if they’re distinct.

Example Configuration 

Service definition:

.platform/services.yaml
searchelastic:
    type: elasticsearch:7.9
    disk: 256

App configuration:

.platform.app.yaml
relationships:
    essearch: "searchelastic:elasticsearch"

Add the Drupal modules 

You will need to add the Search API and Elasticsearch Connector modules to your project. If you are using composer, the easiest way to add them is to simply run:

$ composer require drupal/search_api drupal/elasticsearch_connector

And then commit the changes to composer.json and composer.lock.

Configuration 

Because Drupal defines connection information via the Configuration Management system, you will need to first define an Elasticsearch “Cluster” at admin/config/search/elasticsearch-connector. Note the “machine name” the server is given.

Then, paste the following code snippet into your settings.platformsh.php file.

  • Edit the value of $relationship_name if you are using a different relationship.

  • Edit the value of $es_server_name to match the machine name of your cluster in Drupal.

<?php

// Update these values to the relationship name (from .platform.app.yaml)
// and the machine name of the server from your Drupal configuration.
$relationship_name = 'essearch';
$es_cluster_name = 'YOUR_CLUSTER_HERE';
if ($platformsh->hasRelationship($relationship_name)) {
  $platformsh->registerFormatter('drupal-elastic', function($creds) {
    return sprintf('http://%s:%s', $creds['host'], $creds['port']);
  });

  // Set the connector configuration to the appropriate value, as defined by the formatter above.
  $config['elasticsearch_connector.cluster.' . $es_cluster_name]['url'] = $platformsh->formattedCredentials($relationship_name, 'drupal-elastic');
}

Commit that code and push. The specified cluster will now always point to the Elasticsearch service. Then configure Search API as normal.