es添加索引
public function add(Request $request)
{
//获取数据
$data=$request->post();
//链接es
$client = ClientBuilder::create()->setHosts(config('es.host'))->build();
$params = [
'index' => 'app',
'type' => '_doc',
'body' => [
'title'=>$data['title'],
'img'=>'bkt.clouddn.com/481d1d6fddeb8f15a7fe9ca3520f228d.png',
'icon'=>$data['icon'],
'comment'=>$data['comment'],
'username'=>'星梦'
]
];
//返回索引数据
$rea=$client->index($params);
if ($rea){
//索引添加成功 添加数据库
$res=Tack::insert([
'username'=>'星梦',
'title'=>$data['title'],
'img'=>'bkt.clouddn.com/481d1d6fddeb8f15a7fe9ca3520f228d.png',
'icon'=>$data['icon'],
'comment'=>$data['comment']
]);
//返回数据
return response()->json([
'code'=>200,
'msg'=>'添加成功',
'data'=>$res,
]);
}
}
es 搜索
public function search(Request $request)
{
// 搜索值
$search=$request->input('title');
// 链接es
$client=ClientBuilder::create()->setHosts(config('es.host'))->build();
$params = [
// 数据库名 这里要改成索引
'index' => 'app',
'type' => '_doc',
'body' => [
'query' => [
'match' => [
// 要搜索的字段 替换成你要搜所得字段
'title' => $search
]
],
// 高亮显示操作
'highlight'=>[
// 修改类型操作
'pre_tags'=>["<span style='color: blue'>"],
'post_tags'=>["</span>"],
'fields'=>[
'title'=>new \stdClass(),
]
]
]
];
// 返回值
$res=$client->search($params);
// 将返回值进行处理操作
$datas = $res['hits']['hits'];
// $list=[];
// 循环查询数据
foreach ($datas as &$v){
// 如果高亮搜索存在
// 那么进行数据替换
$v['_source']['title']=$v['highlight']['title'][0];
// 将数据添加之空数组
// $data= array_push($list,$v['_source']);
}
$data=array_column($datas,'_source');
return ['code'=>200,'msg'=>'搜索成功','data'=>$data];
// $data=Tack::get();
// return ['code'=>200,'msg'=>'搜索成功','data'=>$data];
}