Elasticsearch ~2.0不能建立连接-数组到字符串转换错误


Elasticsearch ~2.0 cannot establish connection -array to string conversion error

根据elasticsearch文档,我安装了当前的php库ie2.0,我这样做了

$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();

但它是从buildConnectionsFromHosts方法抛出数组到字符串转换错误。我无法建立连接。

我检查了代码,发现没有代码来处理以数组形式给出的主机。这是在图书馆的bug还是我错过了什么?

谢谢。

解决方案

主机选项中的"password"键应替换为"pass"。

需要修改库中的ClientBuilder.php文件。下面的代码不在elasticsearch-php 2.0 ClientBuilder.php文件中,但在它的主分支中。

我替换了buildConnectionsFromHosts方法

/**
         * @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;
        }

并增加normalizeExtendedHost方法

 /**
     * @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;
    }