1.安装elasticsearch扩展:composer require elasticsearch/elasticsearch
// 构造函数
public function __construct()
{
$params = array(
'127.0.0.1:9200'
);
$this->client = ClientBuilder::create()->setHosts($params)->build();
}
// 获取文档
public function get_doc($id = 1,$index_name = 'employee',$type_name = 'user') {
$params = [
'index' => $index_name,
'type' => $type_name,
'id' => $id
];
$response = $this->client->get($params);
echo '<pre>';
print_r($response);
}
// 更新文档
public function update_doc($id = 1,$index_name = 'employee',$type_name = 'user') {
// 可以灵活添加新字段,最好不要乱添加
$params = [
'index' => $index_name,
'type' => $type_name,
'id' => $id,
'body' => [
'doc' => [
'name' => 'rachel2'
]
]
];
$response = $this->client->update($params);
echo '<pre>';
print_r($response);
}
// 删除文档
public function delete_doc($id = 1,$index_name = 'employee',$type_name = 'user') {
$params = [
'index' => $index_name,
'type' => $type_name,
'id' => $id
];
$response = $this->client->delete($params);
return $response;
}
// 添加文档
public function add_doc($index_name = 'employee',$type_name = 'user') {
$params = [
'index' => $index_name,
'type' => $type_name,
'id' => 3,
'body' => ['name'=>'jason','country'=>'China','age'=>30,'date'=>'2021-10-12']
];
$response = $this->client->index($params);
echo '<pre>';
print_r($response);
}
//查询
public function search(){
$searchParams['index'] = 'employee';
$searchParams['type'] = 'user';
$searchParams['from'] = 0;
$searchParams['size'] = 100;
$searchParams['body']['query']['match']['name'] = 'cherry';
$retDoc = $this->client->search($searchParams);
echo '<pre>';
print_r($retDoc);
}
// 查询文档 (分页,排序,权重,过滤)
public function search_doc($keywords = "cherry",$index_name = "employee",$type_name = "user",$from = 0,$size = 10) {
$params = [
'index' => $index_name,
'type' => $type_name,
'body' => [
'query' => [
'bool' => [
'should' => [
[ 'match' => [ 'age' => [
'query' => 28,
'boost' => 3, // 权重大
]]],
[ 'match' => [ 'name' => [
'query' => $keywords,
'boost' => 2,
]]],
],
],
],
'sort' => ['age'=>['order'=>'asc']]
, 'from' => $from, 'size' => $size
]
];
$results = $this->client->search($params);
echo "<pre>";
print_r($results);
}