Following the elasticsearch documentation I installed the current php library ie 2.0 and I did this
$hosts = [
// This is effectively equal to: "https://username:password!#$?*abc@foo.com:9200/"
[
'host' => 'foo.com',
'port' => '9200',
'scheme' => 'https',
'user' => 'username',
'password' => 'password!#$?*abc'
],
// This is equal to "http://localhost:9200/"
[
'host' => 'localhost', // Only host is required
]
];
$client = ClientBuilder::create() // Instantiate a new ClientBuilder
->setHosts($hosts) // Set the hosts
->build();
But it is throwing array to string conversion error from the buildConnectionsFromHosts method. I am unable to establish connection.
I inspected the code and found that there is no code to process host given in array form.Is this the bug in the library or I am missing something?
Thank you.
The solution
The "password" key in the host options should be replaced with "pass".
The ClientBuilder.php file in the library needs to be modified. The below code is not there in elasticsearch-php 2.0 ClientBuilder.php file but is in its master branch.
I replaced buildConnectionsFromHosts method
/**
* @param array $hosts
*
* @throws \InvalidArgumentException
* @return \Elasticsearch\Connections\Connection[]
*/
private function buildConnectionsFromHosts($hosts)
{
if (is_array($hosts) === false) {
$this->logger->error("Hosts parameter must be an array of strings, or an array of Connection hashes.");
throw new InvalidArgumentException('Hosts parameter must be an array of strings, or an array of Connection hashes.');
}
$connections = [];
foreach ($hosts as $host) {
if (is_string($host)) {
$host = $this->prependMissingScheme($host);
$host = $this->extractURIParts($host);
} else if (is_array($host)) {
$host = $this->normalizeExtendedHost($host);
} else {
$this->logger->error("Could not parse host: ".print_r($host, true));
throw new RuntimeException("Could not parse host: ".print_r($host, true));
}
$connections[] = $this->connectionFactory->create($host);
}
return $connections;
}
and added normalizeExtendedHost method
/**
* @param $host
* @return array
*/
private function normalizeExtendedHost($host) {
if (isset($host['host']) === false) {
$this->logger->error("Required 'host' was not defined in extended format: ".print_r($host, true));
throw new RuntimeException("Required 'host' was not defined in extended format: ".print_r($host, true));
}
if (isset($host['scheme']) === false) {
$host['scheme'] = 'http';
}
if (isset($host['port']) === false) {
$host['port'] = '9200';
}
return $host;
}