Example: Configuring the Selector Classedit

When we changed the logger object, we provided a complete object that we wanted to over-ride the default with. There are many configurations where this won’t work. For example, the Connection class must be instantiated repeatedly when new connections are made.

Rather than provide an anonymous function or callback which builds new objects, the client simply accepts a class path which is used to build new objects.

Let’s configure the Selector class. By default, the client uses a Round-Robin selector (called RoundRobinSelector, unsurprisingly). This will select connections in a loop, evenly distributing requests against your whole cluster.

Let’s change it to a different Selector - the RandomSelector:

$params['selectorClass'] = '\Elasticsearch\ConnectionPool\Selectors\RandomSelector';
$client = new Elasticsearch\Client($params);


The client will now query random nodes. Let’s go one step further and define our own selector, using custom business logic that is specific to your domain. Most configurable components in the client adhere to an interface, which makes it easy to swap them out for your own class.

Let’s make a selector that only chooses the first connection. This is obviously not a good selector (!!!), but it demonstrates the concept well:

namespace MyProject\Selectors;

use Elasticsearch\Connections\ConnectionInterface;
use Elasticsearch\ConnectionPool\Selectors\SelectorInterface

class FirstSelector implements SelectorInterface
{

    /**
     * Selects the first connection
     *
     * @param array $connections Array of Connection objects
     *
     * @return ConnectionInterface
     */
    public function select($connections)
    {
        return $connections[0];
    }

}


And now we can specify that when creating the client:

$params['selectorClass'] = '\MyProject\Selectors\FirstSelector';
$client = new Elasticsearch\Client($params);