namespace tool;
use Elasticsearch\ClientBuilder;
use think\facade\Log;
class Elasticsearch
{
/**
* 创建索引
* @param $index
* @param $param
* @return array
*/
public function createESIndex($index, $param)
{
$client =$this->getClient();
$params = [
'index' =>$index,
'body' => [
'mappings' => [
$index => [
'properties' =>$param
]
]
]
];
$response =$client->indices()->create($params);
return $response;
}
/**
* 删除索引
* @param $index
* @return array
*/
public function deleteESIndex($index)
{
$client =$this->getClient();
$params = ['index' =>$index];
$response =$client->indices()->delete($params);
return $response;
}
/**
* 索引文档
* @param $index
* @param $id
* @param $param
* @return array
*/
public function createDocument($index, $id, $param)
{
$client =$this->getClient();
$params = [
'index' =>$index,
'id' =>$id,
'body' =>$param
];
$response =$client->index($params);
return $response;
}
/**
* 创建索引
* 相当于数据库中建库建表的操作
* @param string $index
* @param array $body
* @return bool
*/
public function createIndex($index ='my_index', $body = [])
{
$client =$this->getClient();
$params = [
'index' =>$index, //索引名称
'body' => [
'settings' => [// 设置配置
'number_of_shards' =>1, //主分片数
'number_of_replicas' =>0 //主分片的副本数
],
'mappings' => [// 设置映射
'_source' => [// 存储原始文档
'enabled' =>'true'
],
'properties' =>$body // 配置数据结构与类型
],
]
];
try {
$response =$client->indices()->create($params);;
}catch (\Exception$e) {
Log::write($e->getMessage(), "创建索引{$index}失败");
return false;
}
return true;
}
/**
* 更新文档
* @param $index
* @param $id
* @param $param
* @return array
*/
public function updateDocument($index, $id, $param)
{
$client =$this->getClient();
$params = [
'index' =>$index,
'id' =>$id,
'body' => [
'doc' =>$param
]
];
$response =$client->update($params);
return $response;
}
/**
* 删除索引
* @param $index
* @param $id
* @return array
*/
public function deleteDocument($index, $id)
{
$client =$this->getClient();
$params = [
'index' =>$index,
'id' =>$id
];
$response =$client->delete($params);
return $response;
}
/**
* es查询
* @param $index
* @param $param
* @return array
*/
public function search($index, $param)
{
$client =$this->getClient();
$params = [
'index' =>$index,
// 'type' => $index,
'body' => [
'query' => [
'match' =>$param
]
]
];
$results =$client->search($params);
return array_chunk($results['hits']['hits'], config('robot.default_think_tips'));
}
/**
* 创建es 客户端
* @return \Elasticsearch\Client
*/
private function getClient()
{
$hosts =config('robot.es_host');
return ClientBuilder::create()->setHosts($hosts)->build();
}
}
网友评论