在 elasticsearch 和 Codeigniter 中解析查询失败

分享于2022年07月17日 codeigniter elasticsearch php 问答
【问题标题】:在 elasticsearch 和 Codeigniter 中解析查询失败(Failed to parse query in elasticsearch and Codeigniter)
【发布时间】:2022-01-20 07:52:27
【问题描述】:

所以我在 codeigniter 中使用这个 library 进行弹性搜索。我想返回大小为 30 的文档

 public function index()
    {
        $data = $this->data;
        $query = '{
            "query" : {
                "match" : {
                    "sch_id" : 45
                }
            }
        }';
        echo "
";
        var_dump($data['elastic']->query_wresultSize('_search',$query,30));
        echo "
"; // return view('dashboard/dashboard',$data); }

但现在显示错误

["root_cause"]=>
    array(1) {
      [0]=>
      array(4) {
        ["type"]=>
        string(21) "query_shard_exception"
        ["reason"]=>
        string(90) "Failed to parse query [{
            "query" : {
                "match" : {
                    "sch_id" : 45
                }
            }
        }]"
        ["index_uuid"]=>
        string(22) "xbrATjiKR_uKtAGN3-GrRw"
        ["index"]=>
        string(7) "article"
      }
    }
["reason"]=>
          string(90) "Failed to parse query [{
            "query" : {
                "match" : {
                    "sch_id" : 45
                }
            }
        }]"
          ["index_uuid"]=>
          string(22) "xbrATjiKR_uKtAGN3-GrRw"
          ["index"]=>
          string(7) "article"
          ["caused_by"]=>
          array(3) {
            ["type"]=>
            string(15) "parse_exception"
            ["reason"]=>
            string(170) "Cannot parse '{
            "query" : {
                "match" : {
                    "sch_id" : 45
                }
            }
        }': Encountered "  ": "" at line 1, column 13.
Was expecting:
    "TO" ...
    "

我只是不知道我做错了什么,因为我没有在查询中使用任何保留字,但它显示了上面的错误

有人可以告诉我我的错误或告诉我另一种方法吗?


【解决方案1】:

我仍然不知道这个 library 中的查询是如何工作的。所以我用 Guzzle 代替。这是我为遇到相同问题的人提供的解决方案。

$uri = 'http://localhost:9200/article/_search/';

        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', $uri, [
                'headers' => [
                        'Accept' => 'application/json',
                        'Accept-Language' => 'en_US',
                        'Content-Type' => 'application/json',
                ],
                'body' => '{
                    "size" : 30,
                    "query" : {
                        "match" : {
                            "sch_id" : 45
                        }
                    }
                }',
            ]
        );

        $data = json_decode($response->getBody(), true);