Elasticsearch多术语搜索Json用PHP查询生成器


Elasticsearch multiple term search Json Query builder with PHP

我正在Codeigniter框架中实现ElasticSearch。我的托管公司不允许在我的托管服务器中提供ES服务,所以我正在使用Facetflow的免费选项测试ES系统,以便在远程服务器上拥有ES。

我正在使用此处提供的ES/Codeigniter库:https://github.com/confact/elasticsearch-codeigniter-library

我可以做一个简单的搜索,但我不得不做一个多术语搜索,因为我不知道如何在不使用ES客户端PHP API的情况下使用PHP构建查询。

我做简单搜索的功能如下:

private function call($path, $method = 'GET', $data = null)
{
    if (!$this -> index) {
        throw new Exception('$this->index needs a value');
    }
    $url = $this -> server . '/' . $this -> index . '/' . $path;
    $headers = array('Accept: application/json', 'Content-Type: application/json', );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    switch($method) {
        case 'GET' :
            break;
        case 'POST' :
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            break;
        case 'PUT' :
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            break;
        case 'DELETE' :
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
            break;
    }
    $response = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    return json_decode($response, true);
}
public function query($type, $q)
{
    return $this -> call($type . '/_search?' . http_build_query(array('q' => $q)));
}

为了调用搜索,我使用

query('','Do My Search');

获取:

curl -XGET 'http://domain/_search?q=Do+My+Search'

需要做些什么来构建创建以下内容的多术语搜索查询?

curl -XGET https://domain/type/_search -d '{ "query": { "filtered": { "query": { "query_string": 
{ "query": "Car For Sale" } }, 
"filter": { "bool" : { "must" : [ 
{"term" : { "provid" : "5" } }, 
{"term" : { "areaid" : "16" } }, 
{"term" : { "catid" : "3" } } ] } } } } }'

您离这里不远了。用JSON编写查询。这可以作为POST请求中的主体传递。call()函数已经处理POST和正文数据。

$path = 'https://domain/type/_search';
$data = '{ "query": { "match_all": {} } }';
call($path, 'POST', $data);

注意:Content-Type: application/json标头不是必需的。实际上,您可以完全省略标头,Elasticsearch将使用JSON进行响应。