Using the PHP Elastica library, I'm wondering what is the best way to check whether a document with Id=1 exists?
I was doing as follows:
$docPre = $elasticaType->getDocument(1);
if ($docPre) {
//do some stuff...
} else {
//do something else...
}
However, the above code does not work because a NotFoundException is thrown by the getDocument() method if the document does not exist.
Alternatively, I could do a type "search" using something like this:
$elasticaQueryString = new \Elastica\Query\QueryString();
$elasticaQueryString->setParam('id', 1);
$elasticaQuery = new \Elastica\Query();
$elasticaQuery->setQuery($elasticaQueryString);
$resultSet = $elasticaType->search($elasticaQuery);
$count = $resultSet->count();
if ($count > 0) {
//do some stuff...
} else {
//do something else...
}
However, the above seems quite cumbersome... What's the better way? This other question applies to ElasticSearch, and one of the answers suggests my first approach (the equivalent to using getDocument). However, I do not want an Exception to be thrown, as it would be the case using Elastica...
Rather than preventing the Exception from being thrown, one way would be to simply deal with it with a "Try, throw and catch" block like this:
try {
$docPre = $elasticaType->getDocument(1);
} catch (Exception $e) {
$docPre = NULL;
}
if ($docPre != NULL) {
//do some stuff...
} else {
//do something else...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With