PHP code example of elastic / transport

1. Go to this page and download the library: Download elastic/transport library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

elastic / transport example snippets


use Elastic\Transport\TransportBuilder;

$transport = TransportBuilder::create()
    ->setHosts(['localhost:9200'])
    ->build();

use Http\Discovery\Psr17FactoryDiscovery;

$factory = Psr17FactoryDiscovery::findRequestFactory();
$request = $factory->createRequest('GET', '/info'); // PSR-7 request
$response = $transport->sendRequest($request);
var_dump($response); // PSR-7 response

use Elastic\Transport\TransportBuilder;

$transport = TransportBuilder::create()
    ->setHosts(['localhost:9200'])
    ->build();

$request = new Request('GET', 'https://domain.com/info');
$response = $transport->sendRequest($request); // the HTTP request will be sent to domain.com

echo $transport->lastRequest()->getUri()->getHost(); // domain.com

use Http\Discovery\Psr17FactoryDiscovery;

$factory = Psr17FactoryDiscovery::findRequestFactory();
$request = $factory->createRequest('GET', '/info'); // PSR-7 request
$promise= $transport->sendAsyncRequest($request);
var_dump($promise); // Promise
var_dump($promise->wait()); // PSR-7 response

$promise->then(function (ResponseInterface $response) {
    // onFulfilled callback, $reponse is PSR-7
    echo 'The response is available';

    return $response;
}, function (Exception $e) {
    // onRejected callback
    echo 'An error happens';

    throw $e;
});

use Elastic\Transport\TransportBuilder;

$transport = TransportBuilder::create()
    ->setHosts([
        '10.0.0.10:9200',
        '10.0.0.20:9200',
        '10.0.0.30:9200'
    ])
    ->build();

$transport->setRetries(1);
$factory = Psr17FactoryDiscovery::findRequestFactory();
$request = $factory->createRequest('GET', '/info'); 
// If a node is down, the transports retry automatically using another one 
$response = $transport->sendRequest($request); 

use Elastic\Transport\NodePool\SimpleNodePool;
use Elastic\Transport\TransportBuilder;

$nodePool = new SimpleNodePool(
    new CustomSelector(),
    new CustomResurrect()
);

$transport = TransportBuilder::create()
    ->setHosts(['localhost:9200'])
    ->setNodePool($nodePool)
    ->build();

use Elastic\Transport\TransportBuilder;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$logger = new Logger('name');
$logger->pushHandler(new StreamHandler('debug.log', Logger::DEBUG));

$transport = TransportBuilder::create()
    ->setHosts(['localhost:9200'])
    ->setLogger($logger)
    ->build();

use Elastic\Transport\TransportBuilder;
use Symfony\Component\HttpClient\Psr18Client;

$transport = TransportBuilder::create()
    ->setHosts(['localhost:9200'])
    ->setClient(new Psr18Client)
    ->build();