Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elastica: Best way to check if document with Id x exists?

Tags:

elastica

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...

like image 323
RayOnAir Avatar asked Mar 21 '23 22:03

RayOnAir


1 Answers

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...
}
like image 189
RayOnAir Avatar answered May 17 '23 08:05

RayOnAir