在PHP中用cURL原生方式查询Elasticsearch数据
说明:操作方式比较简单,对于新手来说难度在于如何去编辑query参数,以下示例列举了两种方式,最常用的是term、range
好处:不用安装第三方库、代码清晰、代码量小
坏处:遇到条件拼装的情况下不方便
参数例子:
//以下查询参数例子可以解决很多常用查询,它就相当于MySQL的where条件,只不过自己需要拼装数组。should、must_not、must不是每个都需要,相当于MySQL的过滤条件(例如must_not 对应 is not null),可选择其中一种或多种。
$query = [
'query' => [
'bool' => [
'should' => [
'range' => [
'height' => ['gt' => 1.8]
]
],
'must_not' => [
'term' => [
'sex' => '女'
]
],
'must' => [
[
'term' => [
'country' => '法国'
]
],
[
'term' => [
'skin' => '白'
]
]
]
]
]
];
以下方法复制可用:
/**
* desc:cURL原始json查询
* author:wh
*
* 其它查询条件参考文档:https://www.cnblogs.com/codeAB/p/10288273.html
*
* eg:
$query = [
'query'=>[
//查询所有
//'match_all'=>[]
//精确查询
'term' => [
//直接查询某个字段的值
'statType' => 'sign'
]
]
];
*
*/
function queryJson($query=[]){
$url = 'http://'.$this->ip.'/_search';
return $this->curl_post($url, json_encode($query));
}
/**
* cURL 网络链接库
* POST
* author:wh
* @param $url 是请求的链接
* @param $postdata 传输的数据,数组格式
* @return bool|int|string
*/
function curl_post( $url, $postdata , $timeout=60) {
$header = array(
'Accept: application/json',
);
//初始化
$curl = curl_init();
//设置抓取的url
curl_setopt($curl, CURLOPT_URL, $url);
//设置头文件的信息作为数据流输出
curl_setopt($curl, CURLOPT_HEADER, 0);
//设置获取的信息以文件流的形式返回,而不是直接输出。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// 超时设置
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
// 超时设置,以毫秒为单位
// curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
// 设置请求头
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE );
//设置post方式提交
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
//执行命令
$data = curl_exec($curl);
// 显示错误信息
if (curl_error($curl)) {
//返回错误码
return ['code'=>curl_errno($curl), 'msg'=>curl_error($curl)];
} else {
//关闭句柄
curl_close($curl);
// 返回的内容
return ['code'=>200, 'msg'=>'ok', 'data'=>$data];
}
}
END