Giter Site home page Giter Site logo

elastic / elasticsearch-php Goto Github PK

View Code? Open in Web Editor NEW
5.2K 463.0 961.0 10.06 MB

Official PHP client for Elasticsearch.

Home Page: https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html

License: MIT License

PHP 98.06% Shell 1.15% Dockerfile 0.09% Twig 0.70%
elasticsearch php client

elasticsearch-php's Introduction

Elasticsearch PHP client

Build status Latest Stable Version Total Downloads

This is the official PHP client for Elasticsearch.

Download the latest version of Elasticsearch or sign-up for a free trial of Elastic Cloud.

Contents


Installation

Refer to the Installation section of the getting started documentation.

Connecting

Refer to the Connecting section of the getting started documentation.

Usage

The elasticsearch-php client offers 400+ endpoints for interacting with Elasticsearch. A list of all these endpoints is available in the official documentation of Elasticsearch APIs.

Here we reported the basic operation that you can perform with the client: index, search and delete.

Versioning

This client is versioned and released alongside Elasticsearch server.

To guarantee compatibility, use the most recent version of this library within the major version of the corresponding Enterprise Search implementation.

For example, for Elasticsearch 7.16, use 7.16 of this library or above, but not 8.0.

Compatibility

The Elasticsearch client is compatible with currently maintained PHP versions.

Language clients are forward compatible; meaning that clients support communicating with greater or equal minor versions of Elasticsearch without breaking. It does not mean that the client automatically supports new features of newer Elasticsearch versions; it is only possible after a release of a new client version. For example, a 8.12 client version won't automatically support the new features of the 8.13 version of Elasticsearch, the 8.13 client version is required for that. Elasticsearch language clients are only backwards compatible with default distributions and without guarantees made.

Elasticsearch Version Elasticsearch-PHP Branch Supported
main main
8.x 8.x 8.x
7.x 7.x 7.17

Backward Incompatible Changes ๐Ÿ’ฅ

The 8.0.0 version of elasticsearch-php contains a new implementation compared with 7.x. It supports PSR-7 for HTTP messages and PSR-18 for HTTP client communications.

We tried to reduce the BC breaks as much as possible with 7.x but there are some (big) differences:

  • we changed the namespace, now everything is under Elastic\Elasticsearch
  • we used the elastic-transport-php library for HTTP communications;
  • we changed the Exception model, using the namespace Elastic\Elasticsearch\Exception. All the exceptions extends the ElasticsearchException interface, as in 7.x
  • we changed the response type of each endpoints using an Elasticsearch response class. This class wraps a a PSR-7 response allowing the access of the body response as array or object. This means you can access the API response as in 7.x, no BC break here! ๐Ÿ‘ผ
  • we changed the ConnectionPool in NodePool. The connection naming was ambigous since the objects are nodes (hosts)

You can have a look at the BREAKING_CHANGES file for more information.

Mock the Elasticsearch client

If you need to mock the Elasticsearch client you just need to mock a PSR-18 HTTP Client.

For instance, you can use the php-http/mock-client as follows:

use Elastic\Elasticsearch\ClientBuilder;
use Elastic\Elasticsearch\Response\Elasticsearch;
use Http\Mock\Client;
use Nyholm\Psr7\Response;

$mock = new Client(); // This is the mock client

$client = ClientBuilder::create()
    ->setHttpClient($mock)
    ->build();

// This is a PSR-7 response
$response = new Response(
    200, 
    [Elasticsearch::HEADER_CHECK => Elasticsearch::PRODUCT_NAME],
    'This is the body!'
);
$mock->addResponse($response);

$result = $client->info(); // Just calling an Elasticsearch endpoint

echo $result->asString(); // This is the body!

We are using the ClientBuilder::setHttpClient() to set the mock client. You can specify the response that you want to have using the addResponse($response) function. As you can see the $response is a PSR-7 response object. In this example we used the Nyholm\Psr7\Response object from the nyholm/psr7 project. If you are using PHPUnit you can even mock the ResponseInterface as follows:

$response = $this->createMock('Psr\Http\Message\ResponseInterface');

Notice: we added a special header in the HTTP response. This is the product check header, and it is required for guarantee that elasticsearch-php is communicating with an Elasticsearch server 8.0+.

For more information you can read the Mock client section of PHP-HTTP documentation.

FAQ ๐Ÿ”ฎ

Where do I report issues with the client?

If something is not working as expected, please open an issue.

Where else can I go to get help?

You can checkout the Elastic community discuss forums.

Contribute ๐Ÿš€

We welcome contributors to the project. Before you begin, some useful info...

  • If you want to contribute to this project you need to subscribe to a Contributor Agreement.
  • Before opening a pull request, please create an issue to discuss the scope of your proposal.
  • If you want to send a PR for version 8.0 please use the 8.0 branch, for 8.1 use the 8.1 branch and so on.
  • Never send PR to master unless you want to contribute to the development version of the client (master represents the next major version).
  • Each PR should include a unit test using PHPUnit. If you are not familiar with PHPUnit you can have a look at the reference.

Thanks in advance for your contribution! โค๏ธ

License ๐Ÿ“—

MIT ยฉ Elastic

elasticsearch-php's People

Contributors

abulhol avatar afrozenpeach avatar alexander-schranz avatar bezhermoso avatar carlcasbolt avatar chrisguitarguy avatar elasticmachine avatar ezimuel avatar feydan avatar hkulekci avatar jamielob avatar joelwurtz avatar jrodewig avatar langergabrielle avatar mhujer avatar najdanovicivan avatar oogfranz avatar paikan avatar philkra avatar picandocodigo avatar polyfractal avatar ramunasd avatar rayward avatar sergeyshcherbin avatar simplechris avatar skolodyazhnyy avatar snapshotpl avatar szabosteve avatar thepanz avatar tomasvotruba avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

elasticsearch-php's Issues

using wildcard or query_string with accent

i'm looking for the way how to search in french.
Can you help me how to query with accent
Exemple med* to mรฉdecin
i try with

$params['body']['query']['query_string']=array(
'analyze_wildcard'=>TRUE,
'analyzer' => "french",
'query' => "" . $word . "");

$results = $this->elasticSearch->search($params);
but it doesn't work
Thanks

Implement StaticNoPingConnectionPool

There should also be a connection pool that performs no pinging, no matter what.

This is useful when your network setup is unable to perform HEAD requests, or you don't want to waste round-trips on pings (but simply want requests to timeout and retry if the node is down).

Related to #18

NodesNamespace problem with info() function

Hello,

I'm writing a function and I want to get all installed plugins.
I'm using the following line, where $client is a parameter of type \Elasticsearch\Client

$client->nodes()->info(array('node_id' => '_all', 'plugin' => TRUE));

This code is throwing this error: plugin is not a valid parameter
I've tried also with 'plugins' but the result is the same.
In the function comments it is written that this is the right syntax.

search() exception when specifing a complex "sort"

I can not apply a sort using the Elasticsearch\Client::search method as outlined below. The bug appears to be in AbstractEndpoint::convertArraysToStrings and it incorrectly attempts to implode() any nested array into a comma separated list but the 'sort' search criteria can be a simple string or another nested array of parameters.

$es = new Elasticsearch\Client();
print_r($es->search(array(
    'index' => 'my_index',
    'type' => 'my_type',
    'sort' => array(
        // 'aFieldName', // this would work ... the next line doesn't
        'dateCreated' => array( 'order' => 'desc' ),
    ),
    'body' => array(
        'query' => array(
            'query_string' => array(
                'query' => 'search term'
            )
        )
    )
)));

How can I get _stats?

Sorry I'm discovering the php api (I was doing all request manually with curl before today) and I was wondering how I could get _stats data with your api?

more_like_this api does not work

Hi there, I just tried to use the mlt endpoint, my request looks like
$query['index'] = 'myIndex'
$query['type'] = 'myType'
$query['id'] = $video['_id'];
$query['min_term_freq'] = 1;
$query['min_term_freq'] = 1;
$query['mlt_fields'] = 'title';
I get:
more_like_this requires 'like_text' to be specified
So than I set the additional parameter $query['like_text'] = 'test';
then I get
Uncaught Exception: like_text is not a valid parameter

this parameter is not even on the whitelist in your endpoint mlt.php so I am wondering how this should work :P.
any idea? bug?
thanks in advance

400 Bad Request on Bulk Update if the id not found

I want to update some Documents with the bulk function. In some cases the id i want to update is not in my index.

In this cases i get the following Exception:

Fatal error: Uncaught exception 'Guzzle\Http\Exception\ClientErrorResponseException' with message 'Client error response
[status code] 400
[reason phrase] Bad Request
[url] http://localhost:9200/products/product/_bulk' in /home/thorsten/import/vendor/guzzle/guzzle/src/Guzzle/Http/Exception/BadResponseException.php:43

Here are my Request and Response from the Commandline:
Request:

curl -X POST "http://localhost:9200/products/product/_bulk" -d '
{"update":{"_id":"10b1894ebb4c44c12146193dff4b4d8d","index":"products","type":"product"}}
{"doc":{"doc_as_upsert":true,"stores":[{"id":"1","price":"45.00","shipping_time":"1"}]}}
{"update":{"_id":"b72dec695f188d99cf6c1b9916884f5c","index":"products","type":"product"}}
{"doc":{"doc_as_upsert":true,"stores":[{"id":"1","price":"43.00","shipping_time":"1"}]}}
{"update":{"_id":"c7212731d67e9731e7c2a9b1657f1dbf","index":"products","type":"product"}}
{"doc":{"doc_as_upsert":true,"stores":[{"id":"1","price":"91.00","shipping_time":"1"}]}}
{"update":{"_id":"ac40fa3f15bbcdf079b97c0f4d2c3eca","index":"products","type":"product"}}
{"doc":{"doc_as_upsert":true,"stores":[{"id":"1","price":"56.00","shipping_time":"1"}]}}
';

Response:

{"took":7,"errors":true,"items":[
{"update":{"_index":"products","_type":"product","_id":"10b1894ebb4c44c12146193dff4b4d8d","status":404,"error":"DocumentMissingException[[products][-1] [product][10b1894ebb4c44c12146193dff4b4d8d]: document missing]"}},
{"update":{"_index":"products","_type":"product","_id":"b72dec695f188d99cf6c1b9916884f5c","_version":2,"status":200}},
{"update":{"_index":"products","_type":"product","_id":"c7212731d67e9731e7c2a9b1657f1dbf","_version":2,"status":200}},
{"update":{"_index":"products","_type":"product","_id":"ac40fa3f15bbcdf079b97c0f4d2c3eca","_version":2,"status":200}}
]}

As you can see the first update statement returns an error but the following updates still working. With the PHP elasticsearch library my update crashs if there is 1 update on an id that doesn't exists.

PHP version requirement

This isn't exactly an issue with the codebase here, but I need help in identifying what it is that makes the php version requirement 5.3.9.

I have been made to try and implement this onto a PHP 5.3.3 system, and it fails completely.

Changing the requirement in composer allows composer to install all of the requirements, however it still fails.

I have no error report to use, as Codeigniter doesn't output errors (because it's so wonderful!)

Any helpful advice would be appreciated.

Facets not working as per docs

If I use:

{
    "query" : {
        "match_all" : {  }
    },
    "facets" : {
        "tag" : {
            "terms" : {
                "field" : "tag",
                "all_terms" : true
            }
        }
    }
}

from the documentation, as a PHP array converted to json by the php-api, the all_terms part doesn't work.

StaticConnectionPool should not ping hosts on initialization

The StaticConnectionPool pings all hosts when it is first initialized, which can cause significant delay as it checks all hosts. For many PHP applications this is a waste of time and resources.

The connection pool should instead only ping hosts before they are used for the first time. The overall flow should look like this:

  1. When connection pool initializes, mark all nodes "dead". This forces all nodes to schedule a ping the first time they are used
  2. Select node
  3. If "alive", return connection
  4. If "dead"
    • If node has not been pinged recently, ping node
      • If ping succeeds, return connection
    • If node has been pinged recently (but still dead), add to skip list
  5. If all nodes are "dead", force ping on each node in skip list, return if alive
  6. If entire skip list fails too, throw exception

Related to #18

Is running of second elasticsearch node (windows: run from bin dir > elasticsearch.bat) splits the load and data to new node?

Hi all,

I am learning elasticsearch on windows.

I have run a node elasticsearch-1.0.0\bin\elasticsearch.bat

it connects on 9200

Then I have create an index using port 9200

it will now insert data using 9200

Now I run another node ( elasticsearch-1.0.0\bin\elasticsearch.bat ) it ll run on 9201

Question 1: Is it splits the load and data to new node as I have only configure port 9200 while creating index?
Question 2: After closing or lost on any node then data will remain available? If yes then in which node?

Thanks
Sohail Ahmed

Documentation doesn't say how to update an indexed document

I'm trying the following and receiving an error:

$params['index'] = 'my_index';
$params['type'] = 'my_type';
$params['id'] = 'document_id';
$params['body'] = array('existing_key' => 'new_value');

$results = $client->update($params);

and I'm receiving the following error:

{"error":"ActionRequestValidationException[Validation Failed: 1: script or doc is missing;]","status":500}

Search endpoint with aggregation queries

Hi,

I'm not able to execute search queries containing aggregations with this client. Though it seems the method used is always GET, that should not be problematic since a direct curl GET query returns the right response with aggregation metrics. Here is a code snippet of the query :

    $params = [
        'index' => 'whatever_index',
        'type' => 'whatever_type',
        'ignore_unavailable' => true,
        'ignore' => [404,500]
    ];
    $params['body'] = <<<JSON
{
    "aggs" : {
        "stats" : {
            "filter" : {
                "bool" : {
                    "must" : [
                        {
                            "term" : {
                                "valid" : true
                            }
                        },
                        {
                            "range" : {
                                "date" : {
                                    "gte" : "{$date_begin}",
                                    "lt" : "{$date_end}"
                                }
                            }
                        }
                    ]
                }
            },
            "aggs": {
                "over_time" : {
                    "date_histogram" : {
                        "field" : "date",
                        "interval" : "day",
                        "time_zone" : "{$timezone}",
                        "format" : "yyyy-MM-dd"
                    },
                    "aggs" : {
                        "types" : {
                            "terms" : {
                                "field" : "_type"
                            },
                            "aggs" : {
                                "unique_hits" : {
                                    "filter" : {
                                        "term" : {
                                            "unique" : true
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    "size": 0
}
JSON;
    $results = $es->search($params);

How to use deleteByQuery function

Hello,

I'm trying to delete some documents using the deleteByQuery function but I'm receiving ActionRequestValidationException[Validation Failed: 1: source is missing;].
From the function description I cannot understand what is wrong with the parameters I'm sending. I've tried to pass 'source' parameter also but the same exception occur.
What is the correct syntax here? I'm using 1.0 version of the library.

$params['index'] = 'yyyy';
$params['type'] = 'xxxx';
$params['body']['query'] = array(
'term' => array(
'entity.entity_id' => $id
)
);

try {
$response = $client->deleteByQuery($params);
}
catch (Exception $e) {
....
}

monolog 1.6.0

Hi,
could you please update the composer.json in your release version 0.4.0 to use the last version of monolog 1.6.0

thank you.

Passing raw json does not work

Hi

It seems passing raw json doesn't work as expected.

I pass the below - when I pass the below in console I get no results as the email '[email protected]' doesn't exist, when I pass via the php client it return every row.
$json = '"filter" : { "nested" : { "path" : "users", "query" : { "match" : { "users.email" : "[email protected]" } } } }';

$params['index'] = 'companies';
$params['type']  = 'company';
$params['body']  = $json;

I then passed:
$json = 'blah blah';

$params['index'] = 'companies';
$params['type']  = 'company';
$params['body']  = $json;

the result was not an error but all the rows.

Please help.

Composer

Hello,

in the composer file, there is a required for php >=5.3.9.

It mean that this library can be used only by php >= 5.4 ? Not by php 5.3.3 ?

Client constructor params

When running the modified version of the Client constructor below, I found that the assigment $this->transport = $this->params['transport']; takes about 40ms.

public function __construct($params = array())
{
$this->setParams($params);
$this->setLogging();

    $start = microtime(true);
    $test = $this->params['transport'];
    var_dump(round(microtime(true) - $start, 2) * 1000 . ' ms');
    var_dump($this->params);

    $this->transport    = $this->params['transport'];
    $this->indices      = $this->params['indicesNamespace'];
    $this->cluster      = $this->params['clusterNamespace'];
    $this->dicEndpoints = $this->params['endpoint'];
}

Have you seen anything like this slow time?

Edit: Ok, I see now how Pimple is using closures to call the Transport class, but in any case, 40ms is still a question mark.

Method to enable TTL

I've just created my own class which extends from \Elasticsearch\Client to create a method to enable the TTL feature on a given index. I would love to see this functionality in the official bundle or i just did not found the method and created a redundancy?

class ElasticSearchClient extends \Elasticsearch\Client {
    public function enableTtl($params) {
        $index = $this->extractArgument($params, 'index');
        $type = $this->extractArgument($params, 'type');
        $body = json_encode(array($type => array('_ttl' => array('enabled' => true))));
        /** @var callback $endpointBuilder */
        $endpointBuilder = $this->dicEndpoints;

        /** @var \Elasticsearch\Endpoints\Update $endpoint */
        $endpoint = $endpointBuilder('Indices\Mapping\Put');
        $endpoint->setIndex($index)
            ->setType($type)
            ->setBody($body);
        $endpoint->setParams($params);
        $response = $endpoint->performRequest();
        return $response['data'];
    }
} 

get() call raising exception on missing document

Is this the intended behaviour? I'm asking because if I query ES directly, it would return me a JSON object with exists:false property, but elasticsearch-php seems to throw a 404 error instead.

Facets

Hi,

How can I do facets grouping of data, e.g. date_histogram, by using elasticsearch-php client?

I tried to send the JSON

{
"query" : {
...
},
"facets": {
    "histo1": {
      "date_histogram": {
        "key_field": "post_date",
        "interval": "month"
      }
    }
  }
}

The ['hits'] gives what match but there is no ['facets'] or something similar for the facets data.

I tried to read the doc on https://github.com/elasticsearch/elasticsearch-php/tree/master/docs, but it doesn't mention facets at all. Please correct if i am wrong and thanks for this elasticsearch php client.

Vic

Body of Search request should accept strings

It should be possible to specify the Search body as a string (e.g. JSON string). The Search endpoint is currently packing string bodies into the 'q' parameter, which is incorrect and opinionated behavior.

The Search endpoint should simply set the body and let the Serializer decide what to do with it.

Note: If a string is provided, no validation should be performed (e.g. to check for valid JSON, etc).

Related to #3

No score on query

I executing a query this is the query
$json='{
"filter": {"term": {
"url": "%s"
}},
"query": {"match": {
"linktext": "%s"
}}
}';
$qStr = sprintf($json,$url,$anchortext);

$params['index'] =get_domain_index($requesturl,"inverted");
$params['type'] ="inverted";
$params['fields'] ="_score,url,referer,linktext";
$params['body'] =$qStr;
$params['sort']="url_date:desc";
$params['size']=100;

try{
    $rc = $GLOBALS['e']->search($params);
}catch (Exception $error){
    echo "Not found\n";
    //echo $error." Error Getting record\n";
}

each record comes back with a NULL score
[98]=>
array(6) {
["_index"]=>
string(10) "inverted-p"
["_type"]=>
string(8) "inverted"
["_id"]=>
string(32) "255718a4b0d3a938360d4d2f92070e40"
["_score"]=>
NULL
["fields"]=>
array(3) {
["linktext"]=>
array(1) {
[0]=>
string(124) "
However when i exectue the same request with Sense I get the score
POST /inver*/_search
{
"filter": {"term": {
"url": "porscheofranchomirage.com"
}},
"query": {"match": {
"linktext": "porsche dealer"
}}
}
"_index": "inverted-p",
"_type": "inverted",
"_id": "be30dd48eea377b389623318186e3141",
"_score": 2.1395235,
"_source": {
"tld": "porscheofranchomirage.com",
"url": "porscheofranchomirage.com",
"referer": "indigoautogroupsocal.com",
"linktext": "Porsche",
"url_date": "2014-03-03"
}
},
{
"_index": "inverted-p",
"_type": "inverted",
"_id": "7582fb1eb94eec4a8fd3f7e0662b3e9d",
"_score": 1.0697618,
"_source": {
"tld": "porscheofranchomirage.com",
"url": "porscheofranchomirage.com",
"referer": "riversidepca.org",
"linktext": "Porsche of Rancho Mirage",
"url_date": "2014-03-03"

Can you please tell how to get the score in my code.

Thanks

Transport Error on All Calls

I'm getting the following error on most calls:

 Missing stream url, the stream can not be opened. This may be caused by a premature call to close().
  • PHP Version: 5.5.9
  • OS: Ubuntu 12.04.4 LTS
  • Nginx: 1.4.6

I'm not using composer for install, did a composer install and then added the files to the repository, including the autoload.php file.
Any ideas what the issue might be?

Bulk Helper

This is a remider to create a great helper for bulk operations.

Take a look at #52

Example code in the documentation gives a warning

Hello there

In the documentation at the paragraph "example usage" there is on line 2 the following use statement "use Elasticsearch;"

this should be "use Elasticsearch as Elasticsearch" because otherwise you get an warning:
" Warning: The use statement with non-compound name 'Elasticsearch' has no effect "

Get final request url?

Hi,
is there a way to retrieve the final url that is generated and used to query ES?
I think this can be very useful for unit testing and debugging.

Thanks

Using artax instead of guzzle

Heya cool people of elasticsearch!

Just a random thought i had and thought of doing in my own elasticsearch code before i found this project was to utilize artax (https://github.com/rdlowrey/Artax) to run requests in parallel stuff like searching/count would be pretty neat to be able to have run parallel

Bulk operations

Sorry, but are bulk operations already available? Will it be?

Detect and bypass the dead hosts. How to do it quickly?

Hi Zachary and other guys,

Say I have a number of hosts and some are dead, if I understand correctly, it takes 60 seconds to confirm the host is dead. In some cases, it's just too long and I am looking for a quicker way to test host and skip it if it is dead and go for another one.

Should I change the configuration (sorry I can't find option in http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/_configuration.html) to lower the timeout? or there are other approaches?

Thanks for reading. :)

Set logPath

Hi

i setup logPath to some value but when i run script i see error:
The stream or file "elasticsearch.log" could not be opened: failed to open stream in class monolog/monolog/src/Monolog/Handler/StreamHandler.php.

When i trace it i find the path in url property is without path i see that only elasticsearch.log value remain and whole path set in logPath is gone.

Raw json

Hello

I'm trying to search an index with a raw json object.
I aint getting the desired results so i went searching in the code and found something that isn't clear to me.

in \Elasticsearch\Client

 $endpoint = $endpointBuilder('Search');
        $endpoint->setIndex($index)
                 ->setType($type)
                 ->setBody($body);
        $endpoint->setParams($params);

You first set the body and then the params.

in \Elasticsearch\Endpoints\Search
the setBody method:

if (is_string($query) === true) {
            $this->params['q'] = $query;
            $this->body = null;
        }

here is the raw json string added to the params array.
Then in setParams the 'q' key in the params array will be overwritten with $this->convertArraysToStrings($params); so my json is gone and no search is done.

    public function setParams($params)
    {
        $this->checkUserParams($params);
        $this->params = $this->convertArraysToStrings($params);
        $this->extractIgnore();

        return $this;
    }

This is my code:

 $json = '{
            "query" : {
                "match" : {
                    "name" : "' . $city . '"
                }
            }
        }';
$searchParams = array();
$searchParams['index'] = $indexName;
$searchParams['type']  = $indexType;
$searchParams['body'] = $querystring;
$queryResponse = $this->es->search($searchParams);

Thnx in advance!

Getting different (wrong) result when using PHP client

Hello,

I am just trying out the Elasticsearch PHP client for the first time.
Now I am getting a strange result, when counting objects in an index.

But from the beginning:
I wrote a small PHP script which adds 2 document to an index called "test".
Afterwards I wanted to valid the inserts by counting the objects in the index.

Calling
curl -XGET 'http://localhost:9200/test/_count?pretty=true'
gives me:

Array
(
    [count] => 2
    [_shards] => Array
        (
            [total] => 5
            [successful] => 5
            [failed] => 0
        )
)

which is correct.
However using:

$result = $client->count(array('index' => 'test'));

there are zero document in $result['count'].
I was already double checking the client log and did not find a solution.

Any ideas ?

Connection ping only works for timeouts, should also catch dns faillure or node down

The ping method in AbstractConnection is too lazy for me, here is the code:

        try {
            $response = $this->performRequest('HEAD', '', null, null, $options);

        } catch (OperationTimeoutException $exception) {
            $this->isAlive = false;
            return false;

        }

We only catch timeouts, but there is a lot of Exceptions that may occurs here:

  • CouldNotResolveHostException
  • CouldNotConnectToHost
  • OperationTimeoutException
  • TransportException

If thinks the 4 of them needs to be catched, if a node goes down (issue or server maintenance) I do not want my whole application to fail.

What do you think about it?

The real issue is, with this code:

        $params = array('hosts' => array (
            '127.0.0.1:9200',
            '127.0.0.1:9201',
        ));
        $this->client = new Client($params);

As the second node does not respond at all, the whole client is crashed with a CouldNotConnectToHost exception - we can't use the first node at all.

No exception thrown with bad host credentials

Running 0.4.3 currently. Had some DNS updates that hadn't taken yet and attempting to create an index threw a php error at following location:

Undefined index: data
vendor/elasticsearch/elasticsearch/src/Elasticsearch/Namespaces/IndicesNamespace.php @ line 777

return $response['data'];

Once DNS had updated the call worked fine, which means client was just talking params, running the index create call and attempting to just return the data param sans checking for issues.

Side note, tried same call passing no host param and exception was correctly thrown

Invalid constructor arguments results in invalid response status

If you pass invalid arguments to the Elasticsearch\Client constructor, the error will cause the HTTP return status to be 0 , which will cause the web server to discard the error and return a 502 Bad Gateway

Software stack:

  • Nginx 1.4.1
  • php 5.3.10-1ubuntu3.9 (fpm-fcgi)
  • Xdebug 2.1.0

Production steps:

$options = array();
// do not give a host.
$client = new Elasticsearch\Client($options);

Resulting output in nginx error log:

upstream sent invalid status "0 Hosts parameter must be an array of strings" while reading response header from upstream

function_score not working?

hi folks,

i try to pass a function_score request but it doesn't work.

$json = '{
"query": {
"function_score": {
"functions": [
{
"random_score": {

                   }
                }
             ],
             "boost_mode": "replace",
             "query": {
                "match_all": {}
             }
          }
       }
    }';

    $qry = array(
        'query' => array(
            'function_score' => array(
                'functions' => array(
                    array('random_score' => array())
                ),
                'query' => array(
                    array('match_all' => array())
                )
            )
        )
    );

    $searchParams['body']['query']['function_score']['functions']['random_score'] = array();
    $searchParams['body']['query']['function_score']['query']['match_all'] = array();

    //$searchParams['body'] = $qry;

    $retDoc = $elastic->search($searchParams);

if i pass $query i will get a exception: function_score: malformed query, expected a START_OBJECT while parsing functions but got a FIELD_NAME.

If i pass $json, it works. I'm not sure what i'm doing wrong.

Thanks

HTTP basic auth support?

Just wanted to check if there's any way to pass username/password credentials when configuring the connection?

Thanks!

multisearch return NULL instead of array

For some request msearch() method return NULL instead array of responses.

Small sample:

$params = array(
    'hosts' => array('127.0.0.1'),
    'connectionClass' => '\Elasticsearch\Connections\CurlMultiConnection',
    'connectionParams' => array(
        'curlOpts' => array(
            CURLOPT_HTTPHEADER => array('Connection: keep-alive', 'Keep-Alive: 300')
        )
    )
);
$elastic = new \Elasticsearch\Client($params);

$params = array(
    'index' => 'Ads',
    'body' => array(
        array('type' => 'DefManagedBids'),
        array(
            'fields' => array('g', 'hta', 'cap', 'cTtl'),
            'query' => array(
                'filtered' => array(
                    'filter' => array(
                        'and' => array(
                            array('term' => array('sc' => 9000081)),
                            array('terms' => array('adtypes' => array('image_26', 'richmedia_26'))),
                            array('term' => array('countries' => 'HK')),
                            array('term' => array('languages' => 'LG')),
                            array('terms' => array('keywords' => array(
                                '348a448a51d1e0f0f5eee42337d12adc',
                                '8f99e430f3167d6bf65e0beb23896276',
                                '9336ebf25087d91c818ee6e9ec29f8c1',
                                'ee2a23af409b352d8f1819405bc770b2',
                                'ee8147f3ad132c3495314bb77fefa274',
                                'f3aa047479dae4b554c381ccbc2f5019',
                                'fe325cf304ee9155d513be1044bf064b',
                                'dbab14a2fd9a474f5aa30b06f130b368'
                            )))
                        )
                    )
                )
            )
        ),
        array('type' => 'DefRonBids'),
        array(
            'fields' => array('g', 'hta', 'cap', 'cTtl'),
            'query' => array(
                'filtered' => array(
                    'filter' => array(
                        'and' => array(
                            array('terms' => array('adtypes' => array('image_26', 'richmedia_26'))),
                            array('term' => array('countries' => 'HK')),
                            array('term' => array('languages' => 'LG')),
                            array('terms' => array('keywords' => array(
                                '348a448a51d1e0f0f5eee42337d12adc',
                                '8f99e430f3167d6bf65e0beb23896276',
                                '9336ebf25087d91c818ee6e9ec29f8c1',
                                'ee2a23af409b352d8f1819405bc770b2',
                                'ee8147f3ad132c3495314bb77fefa274',
                                'f3aa047479dae4b554c381ccbc2f5019',
                                'fe325cf304ee9155d513be1044bf064b',
                                'dbab14a2fd9a474f5aa30b06f130b368'
                            )))
                        )
                    )
                )
            )
        )
    )
);

$result = $elastic->msearch($params);

If I perform the same request with curl it show correct response:

{"responses":[{"took":0,"timed_out":false,"_shards":{"total":2,"successful":2,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}},{"took":0,"timed_out":false,"_shards":{"total":2,"successful":2,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}}]}

If I perform the same request with other values for search criteria it work properly and return array of responses for each query.

Please let me know if you need additional details.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.