I am looking at #37 but I am trying to wrap my head around this. so when I do this:
$params = array(
'id' => $id,
'type' => $type,
'index' => $index,
);
$response = $this->Client->get($params);
For whatever reason an exception is thrown when a document is not found, but if I do this:
$params = array(
'id' => $id,
'type' => $type,
'index' => $index,
'ignore' => 404
);
$response = $this->Client->get($params);
I bypass the exception thrown but now I get a json string instead?
'{"_index":"test","_type":"pets","_id":"yim-XEJgRImt-Cos6h2FtAd","found":false}'
And this is the intended behavior?
Yep, that's intended behavior.
Elasticsearch has two ways to signal an error: the HTTP status code is changed (400, 404, etc) and a response body contains the error (sometimes as JSON, sometimes as a big Java stack trace).
The default behavior of Elasticsearch-PHP is to raise an exception when ES throws an error. This tends to make handling errors easier, since you can catch all exceptions and handle each different variety, rather than trying to parse the JSON or stacktrace.
If you apply the ignore flag, it tells Elasticsearch-PHP to not throw exceptions for that particular HTTP response code(s). Since an exception isn't thrown, you get back whatever the response body was...and you can do anything you want with it.
In the case of a missing doc during GET, you'd probably want to parse the JSON and extract "found: false".
Got it. Thanks for clearing that up. Personally, I prefer exceptions thrown so I will continue to use the following snippet:
public function fetchDocument($id, $type, $index = null) {
$index = $this->_getIndex($index);
$params = array(
'id' => $id,
'type' => $type,
'index' => $index,
);
/*
* https://github.com/elasticsearch/elasticsearch-php/issues/37 explains why we need
* to catch exceptions for documents not found
*/
try {
$response = $this->Client->get($params);
} catch (Exception $e) {
if ($e->getCode() == '404' && json_decode($e->getMessage(), true)) {
$response = json_decode($e->getMessage(), true);
} elseif ($e->getCode() == '400') {
return array();
} else {
throw $e;
}
}
if ($response['found']) {
$result = array('id' => $response['_id']) + $response['_source'];
return array($result);
}
return array();
}
Yeah, I prefer exceptions too. You can catch specific exceptions too, for example:
try {
$response = $this->Client->get($params);
} catch (Missing404Exception $e) {
// Stuff for missing docs
} catch (Exception $e) {
// Everything else
}
Most helpful comment
Yeah, I prefer exceptions too. You can catch specific exceptions too, for example: