【问题标题】:Elasticsearch multiple term search Json Query builder with PHPElasticsearch 多词搜索 Json Query builder with PHP
【发布时间】:2016-02-16 17:32:26
【问题描述】:

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

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

我可以做一个简单的搜索,但我坚持做一个多词搜索,因为我不明白如何在不使用 ES Client 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" } } ] } } } } }'

【问题讨论】:

    标签: php json codeigniter elasticsearch


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 2013-08-13
      • 2014-11-18
      • 1970-01-01
      相关资源
      最近更新 更多