/** 提前声明 ElasticSearch 私有属性 方便以下使用
* @var
*/
private $es;
/** ElasticSearch的前提 下载 composer require elasticsearch/elasticsearch
*
* Uploads constructor.
* @param Request|null $request
*/
public function __construct(Request $request = null)
{
parent::__construct($request);
// 这里是地址:127.0.0.1:9200 位于本机地址
$hosts = config('host');
$this->es = ClientBuilder::create()->setHosts($hosts)->build();
}
/**
* 初始化 ElasticSearch,并生成索引,_doc为7.0后默认的类型,所以不用加,加的话报错
*/
public function ElasticSearch()
{
$params = [
'index' => 'uploads',
'body' => [
'settings' => [
'number_of_shards' => 3,
'number_of_replicas' => 2
],
'mappings' => [
// '_doc' => [
'_source' => [
'enabled' => true
],
'properties' => [
'music' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
],
'video' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
]
]
// ]
]
]
];
$response = $this->es->indices()->create($params);
dd($response);
}
/** 添加ElasticSearch
*
* @param Request $request
*/
public function save(Request $request)
{
$param = $request->param();
$model = \app\video\model\Uploads::create($param,true);
// 写文档
$params = [
'index' => 'uploads',
'type' => '_doc',
'id' => $model->id,
'body' => [
'music' => $model->music,
'video' => $model->video,
],
];
$response = $this->es->index($params);
dd($response);
}
/** 搜索并高亮显示 安装 composer require nunomaduro/collision 即可,为高亮做准备,前端可设置颜色 em : {color : red}
* @param Request $request
*/
public function search(Request $request)
{
$param = $request->param('music');
$params = [
'index' => 'uploads',
'body' => [
'query' => [
'multi_match' => [
'query' => $param,
'fields' => ['music','video']
]
],
'highlight' => [
'fields' => [
"*" => new Highlighter()
]
]
]
];
$response = $this->es->search($params);
print_r($response);
}
/** 进行修改
* @param Request $request
* @param $id
*/
public function update(Request $request,$id)
{
$param = $request->param();
$model = \app\video\model\Uploads::update($param,['id'=>$id],true);
// 写文档
$params = [
'index' => 'uploads',
'type' => '_doc',
'id' => $model->id,
'body' => [
'music' => $model->music,
'video' => $model->video,
],
];
$response = $this->es->index($params);
dd($response);
}
/** 进行删除
* @param Request $request
* @param $id
*/
public function delete(Request $request,$id)
{
// 进行删除数据
\app\video\model\Uploads::destroy($id);
$params = [
'index' => 'uploads',
'id' => $id
];
$response = $this->es->delete($params);
dump($response);
}
// 这里是我自己写的备注,请勿与上面一块粘贴
$name = $request->name;
$data = Book::when($name, function ($query, $name) {
$query->where('name','like', "%{
$name}%");
})->paginate(5)->appends($request->all());
Laravel/Tp5--ElasticSearch--增删改查-----高亮显示
猜你喜欢
转载自blog.csdn.net/zhouqi1427/article/details/114707744
今日推荐
周排行