- 本文适用于laravel5*
- 安装curl扩展
参考网站
https://packagist.org/packages/ixudra/curl?tdsourcetag=s_pctim_aiomsg
在composer.json文件中的require中加入
"ixudra/curl": "6.*",
安装curl扩展.png
或者
运行
composer require ixudra/curl
2.配置curl扩展
在config/app.php的providers数组中加入一段
Ixudra\Curl\CurlServiceProvider::class,
在config/app.php的aliases数组中加入一段
'Curl' => Ixudra\Curl\Facades\Curl::class,
接下来就可以使用curl扩展了
- 添加
$jsonData=json_encode($data,true);
$esRes=Curl::to($this->esPortUrl.$index.'/'.$type.'/'.$id)
->withData($jsonData)//传输数据
->withContentType('application/json')//头
->post();
$res=json_decode($esRes,true);
if(isset($res['error'])){
//有错误
return $this->returnJson('9'.$res['status'],$res['error']['type'],$res['error']['caused_by']);
}
return $this->returnJson('9200','index:'.$index.';type:'.$type.';id:'.$res['_id'],$res);
- 展示
$url='http://127.0.0.1:9400/'.$index.'/'.$type.'/_search';
$esRes=Curl::to($url)
->get();
$resArr=json_decode($esRes,true);
if(isset($resArr['error'])){
return $this->returnJson('9'.$resArr['status'],$resArr['type'],$resArr['root_cause']);
}
return $this->returnJson('9200','success',$resArr);
- 搜索高亮分页
$url=$this->esPortUrl.$index.'/'.$type.'/_search';
$data = [
"query"=>[
"match"=>[
"name"=>"$search"
]
],
"from" => ($page-1)*3,
"size" => 3,
"highlight" => [
"pre_tags" => ["<font color='red'>"],
"post_tags" => ["</font>"],
"fields" => [
"name" => new \stdClass()
]
]
];
$res = Curl::to($url)
->withData(json_encode($data))
->withContentType('application/json')
->post();
$resArr=json_decode($res,true);
$arr=[];
foreach ($resArr['hits']['hits'] as $v){
$arr[]=array_merge(['id'=>$v['_id']],$v['_source']);
}
//将es数据拼接成跟数据库格式一样
return $arr;