使用PHP Elastica库,我想知道检查Id = 1的文档是否存在的最佳方法是什么?
我做的如下:
$docPre = $elasticaType->getDocument(1);
if ($docPre) {
//do some stuff...
} else {
//do something else...
}
Run Code Online (Sandbox Code Playgroud)
但是,上面的代码不起作用,因为如果文档不存在,则getDocument()方法抛出NotFoundException.
或者,我可以使用以下内容进行类型"搜索":
$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...
}
Run Code Online (Sandbox Code Playgroud)
但是,上面看起来相当麻烦......有什么更好的方法? 这个问题适用于ElasticSearch,其中一个答案表明我的第一种方法(相当于使用getDocument).但是,我不希望抛出异常,因为使用Elastica就是这种情况......
而不是阻止抛出异常,一种方法是简单地用"Try,throw and catch"块处理它,如下所示:
try {
$docPre = $elasticaType->getDocument(1);
} catch (Exception $e) {
$docPre = NULL;
}
if ($docPre != NULL) {
//do some stuff...
} else {
//do something else...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2429 次 |
| 最近记录: |