将弹性搜索查询转换为Elastica

时间:2015-05-07 16:50:24

标签: php elasticsearch elastica

我的弹性搜索查询为:

{
  "query": {
    "bool": {
      "must": [ 
       {
       "match": {"title": "accountant"}
       },
       {
          "nested": {
            "path": "schools", 
            "query": {
              "bool": {
                "must": [ 
                  { "match": { "schools.school_name": "Duke University" }}
                ]
        }}}}
      ]
}}}

我正在使用php的Elastica库,我想将此原始查询转换为Elastica。我知道我可以从Elastica运行原始查询,但我更喜欢使用Elastica类。我尝试过thisthis。但它们都不起作用。这是我当前代码的简化版本:

$schoolsTermFilter = new \Elastica\Filter\Term(['schools.school_name' => "Duke University"]);
$schoolsBoolFilter = new \Elastica\Filter\Bool();
$schoolsBoolFilter->addMust($schoolsTermFilter);

$nestedFilter = new \Elastica\Filter\Nested();
$nestedFilter->setPath("schools");
$nestedFilter->setFilter($schoolsBoolFilter);

$boolFilter = new \Elastica\Filter\Bool();
$boolFilter->addMust($nestedFilter);

$query->setPostFilter($boolFilter);

但是,这会返回空结果。原始查询确实返回结果,所以我知道我应该得到一些东西。有人可以帮助我吗?感谢

2 个答案:

答案 0 :(得分:6)

这是QueryBuilder版本(> = v1.4.2.0):

$qb = new \Elastica\QueryBuilder();

$query = new \Elastica\Query(
    $qb->query()->bool()
        ->addMust($qb->query()->match(
            'title',
            'accountant'
        ))
        ->addMust($qb->query()->nested()
            ->setPath('schools')
            ->setQuery(
                $qb->query()->bool()
                    ->addMust($qb->query()->match(
                        'schools.school_name',
                        'Duke University'
                    ))
            )
        )
);

答案 1 :(得分:3)

以下是Elastica的1:1翻译供您查询:

$query = new \Elastica\Query();

$matchQuery = new \Elastica\Query\Match();
$matchQuery->setField("title", "accountant");

$schoolsTermQuery = new \Elastica\Query\Match();
$schoolsTermQuery->setField("schools.school_name", "Duke University");
$schoolsBoolQuery = new \Elastica\Query\Bool();
$schoolsBoolQuery->addMust($schoolsTermQuery);

$nestedQuery = new \Elastica\Query\Nested();
$nestedQuery->setPath("schools");
$nestedQuery->setQuery($schoolsBoolQuery);

$boolQuery = new \Elastica\Query\Bool();
$boolQuery->addMust($matchQuery);
$boolQuery->addMust($nestedQuery);

$query->setQuery($boolQuery);

print_r(json_encode($query->toArray()));

您粘贴的Elasticsearch查询不包含过滤器,仅包含查询。因此,Elastica翻译不应使用来自\Elastica\Filter但来自\Elastica\Query的对象。此外,如果要在Elasticsearch中使用之前验证查询,可以使用$query->toArray()进行打印。