- 本文適用于laravel5*
- 安裝curl擴展
參考網(wǎng)站
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數(shù)組中加入一段
Ixudra\Curl\CurlServiceProvider::class,
在config/app.php的aliases數(shù)組中加入一段
'Curl' => Ixudra\Curl\Facades\Curl::class,
接下來就可以使用curl擴展了
- 添加
$jsonData=json_encode($data,true);
$esRes=Curl::to($this->esPortUrl.$index.'/'.$type.'/'.$id)
->withData($jsonData)//傳輸數(shù)據(jù)
->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數(shù)據(jù)拼接成跟數(shù)據(jù)庫格式一樣
return $arr;
