문제

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...
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top