ElasticSearch是一个基于RESTful web接口的分布式全文搜索引擎。 本解决方案是基于Mysql数据库 、 Hadoop生态(可选)、 ElasticSearch搜索引擎三大数据系统实现一个分布式 全文搜索系统。 主要包括数据接入、数据索引和全文搜索3个模块。适用于各种项目的各种搜索场景。
在我们使用es之前需要进行一些公共文件和封装类的引用
创建索引:创建索引添加索引‘index’和表’type‘以及进行高亮显示的配置
//创建索引,并且设置ik分词器
public function suoyin2()
{
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$params = [
'index' => 'qxw',
'body' => [
'settings'=>[
'number_of_shards'=>5, //分片数量(后期不可更改)
'number_of_replicas'=>1 //副本数量(后期可更改)
],
'mappings'=>[
// 'table'=>[
// 'enabled'=>true //php版本7.0之后表名默认为‘_doc’,表名可以不加
// ],
//加载ik分词器的字段
'properties' => [
'title' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
],
'content' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
],
]
],
]
];
$response = $client->indices()->create($params);
}
当我们添加到数据表后的数据然后进行倒叙排序取出添加数据然后调用封装类进行es同步
public function save(Request $request)
{
//接收数据
$param=$request->param();
//验证
$validate=$this->validate($param,[
'name'=>'require',
'ktime'=>'require',
'jtime'=>'require',
'shop'=>'require',
'number'=>'require',
]);
if ($validate !== true){
$this->fail($validate);
}
//添加
try {
$obj=new \app\day5\model\es();
$res=$obj->allowField(true)->save($param);
//将添加的数据再添加到es中
$es=new MyElasticsearch();
$data=\app\day5\model\es::order('id','desc')->limit(1)->find()->toArray();
//halt($data->id);
//var_dump($data);die();
$add=$es->add_doc($data['id'],$data,'ysb','_doc');
return redirect('index')->with(['msg'=>'添加成功']);
}catch (Exception $e){
$this->fail('添加失败');
}
}
然后查询的时候对其进行判断:如果input搜索框没有数据那就去数据表进行查找,如果有搜搜值就去es里面进行全文搜索
public function index(Request $request)
{
//接收每页显示条数和每页限制条数
$page=$request->param('page');
$limit=$request->param('limit');
//接收搜索的标题
$name=$request->param('name');
// $where=[];
// if ($name){
// $where['name']=['like',"%$name%"];
// }
// if ($request->isAjax()){
// $data=\app\day5\model\es::where($where)->page($page,$limit)->select();
// //获取总条数
// $count=\app\day5\model\es::where($where)->count();
// return ['code'=>'0','data'=>$data,'count'=>$count,'msg'=>'查询成功'];
// }
// return view('index');
if ($request->isAjax()){
if ($name == ''){
$data=\app\day5\model\es::page($page,$limit)->select();
//获取总条数
$count=\app\day5\model\es::count();
return ['code'=>'0','data'=>$data,'count'=>$count,'msg'=>'查询成功'];
}else{
//从es中查询
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$params = [
'index' => 'ysb',
'body' => [
'query' => [
'multi_match' => [
'query' => $name,
//查询字段
'fields' => ['name']
]
],
//高亮显示
'highlight' => [
"pre_tags" => ["<em class='yx_hl' style='color: red'>",],
"post_tags" => [ "</em>"],
'fields' => [
'*' => new Highlighter()
]
]
]
];
$response = $client->search($params);
//print_r($response);die();
//降维
$data = array_column($response['hits']['hits'], 'highlight');
return ['code' => 0, 'msg' => '查询成功', 'data' => $data];
}
}
return view('index');
}