lalavel的弹性搜索 - 获取与一个或多个类别匹配的文档?

时间:2016-03-25 21:05:47

标签: php laravel elasticsearch elasticsearch-plugin

以下代码适用于我并返回与查询匹配的博文

 $params = [
            'index' => 'blog',
            'type' => 'post',
            'body' => [
                'query' => [
                    'multi_match' => [
                        'query' => $request->get('query'),
                        'fields' => ['title', 'description']
                    ]
                ]
            ]
        ];
$response = \Elasticsearch::search($params); // works perfect

如何更改上面的代码,以便我可以获取其类别与 $ categories 值之一匹配的所有文档

$ categories变量是我从复选框中获取的变量

我尝试使用下面的代码但由于某种原因它返回空结果:

 // $categories = $request->get('categories');
 $categories = ["News", "Technology"];
 $params = [
            'index' => 'blog',
            'type' => 'post',
            'body' =>  [

                "query"=> [
                    "filtered"=> [
                        "query"=> [
                            "match_all"=> []
                        ],
                        "query"=>[
                            "terms"=> [
                                "category"=> $categories
                            ]
                        ]

                    ]
                ]
            ]
        ];

 $response = \Elasticsearch::search($params); // return 0 hits

有关如何根据一个或多个类别获取文档而不是根据匹配的单词获取文档的任何想法?

1 个答案:

答案 0 :(得分:0)

您在query子句中的同一级别有两个filtered子句,这是不允许的。

"query"=> [
                    "filtered"=> [
                        "query"=> [  <-- (1)
                            "match_all"=> []
                        ],
                        "query"=>[ <-- (2)
                            "terms"=> [
                                "category"=> $categories
                            ]
                        ]

                    ]

如果您只尝试查询类别,则应删除第一个子句。您可以将查询编写为

                  "query"=> [
                    "filtered"=> [
                        "query"=>[
                            "terms"=> [
                                "category"=> $categories
                            ]
                        ]
                     ]  
                    ]