Curl实现ElasticSearch的增删改查

时间:2023-03-09 09:12:04
Curl实现ElasticSearch的增删改查

一、添加数据(laravel必须安装Curl扩展)

$data = [
'username'=>"张三",
'sex'=>"女",
'age'=>“12”,
'habby'=>"看书"
'create_time'=>time()
];
$response = Curl::to("http://localhost:9200/users/adduser")//http://localhost:9200/_index/_type
->withData(json_encode($data))
->withContentType("application/json")
->post();
$res=json_decode($response,true);
$data['sid']=$res['_id'];
$this->result['code']=200;
$this->result['message']="ok";
$this->result['data']=$response;
return $response;

二、数据删除

$response = Curl::to("http://127.0.0.1:9200/user/adduser/-v08VGoBKruRPXlHAPOO")//http://localhost:9200/_index/_type/_id(添加数据生成随机id,最好不要写成死值)
->withContentType("application/json")
->delete();
return $response;

三、数据修改

$data = [
'username'=>"张三",
'sex'=>"女",
'age'=>“13”,
'habby'=>"看书"
'create_time'=>time()
];

$response = Curl::to("http://localhost:9200/user/adduser/-v08VGoBKruRPXlHAPOO")   //http://localhost:9200/_index/_type/_id(添加数据生成随机id,最好不要写成死值)
->withData(json_encode($data))
->withContentType("application/json")
->post();
return $response;

四、数据查询

$response = Curl::to("http://127.0.0.1:9200/user/adduser/_search")  //http://localhost:9200/_index/_type/_search
->withContentType("application/json")
->post();
return $response;

五、数据分页,高亮显示

public function page($username,$value,$page){
$params = [
'query' => [
'match_phrase' => [
"$username" => "$value",
]
],
"size"=>3,
"from"=>$page,
'highlight'=>[
"pre_tags" => ["<font color='red'>"],
"post_tags"=>["</font>"],
'fields'=>[
"$username"=>new \stdClass()
]
]
];

$res=Curl::to("http://localhost:9200/user/adduser/_search")
->withData(json_encode($params))
->withContentType('application/json')
->post();
return $res;
}

laravel框架实现,路由如下:Route::any("User/page/{username}/{value}/{page}","UserController@page");