简体   繁体   中英

Set Content-type header to Elasticsearch-php client

I'm trying to use Elasticsearch-php version 5.0 to send search queries to Elasticsearch 6.4.2.

One of the breaking changes from 5.0 to 6.0 is that there is the " strict content type validation " which means that requests to Elasticsearch must sent with "Content-type: application/json" header.

In order to add this header, I tried to use polyfractal's suggestion from this thread :

    $params = [
    'index' => $index,
    'type' => $mapping,
    'body' => $query,
    'client' => [
        'curl' => [CURLOPT_HTTPHEADER => array('Content-type: text/plain')]
        ]
    ];

    $res = $this->mESClient->search($params); // this is Elasticsearch/Client

    return $res;

but for some reason, I keep getting "Notice: Array to string conversion" when the code tries to do curl_setopt_array() , and the request is net sent.

Please note: that when I remove the 'client' part of the $params array the request is being received in the Elasticsearch.

According to Version Matrix , you should use elasticsearch-php 6.0 when dealing with ES >=6.

elasticsearch-php 5.0 is not compatible with ElasticSearch 6.

The thread you mentioned, relates to ES-PHP 1.x/2.x, which may have different syntax for options. It's not relevant for your situation, except that one of comments says the same that I just did above.

FYI, if you're using Elasticsearch 6.0+, you need to upgrade your ES-PHP client to the 6.0 branch too. ES-PHP 6.0+ sets the content-type headers automatically: fd3b0f1

Found the problem. It seems that there is a buggy functionality when trying to set HTTP headers using curl and specifying authorization details in the URL.

for example: https:// username:password @host:port

For some reason the client copies the curl http headers into other curl options (that requires string and not array) and, therefore, the exception of Array to string conversion thrown from curl_setopt_array.

When I removed the authorization details from the host URL and used the curl authorization header everything worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM