看代码:
$params = [ 'index' => "goods", 'body' => [ 'mappings' => [ 'properties' => [ //之后可以进行搜索的字段 'name' => ['type' => 'text',"analyzer" => "ik_max_word","search_analyzer" => "ik_max_word" ] ] ] ] ]; $this->client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();// 执行 只用执行一次即可// $this->client->indices()->create($params);
添加es中的表,index 表示表名 body 表示主体部分,然后执行,可以创建一个es 中的表格,相当于数据库中的数据表,现在还是空的表格,需要添加数据后在进行查询
添加:
$goods = $goods->toArray(); $params = [ 'index' => 'goods', 'type' => '_doc', 'body' => $goods ]; //执行添加 return $this->client->index($params);
先查询出添加数据库的数据,转为数组格式添加进es中 方便在随后的搜索中实现搜索
搜索:
//判断用户是否搜索,如果没有则跳过 if ($search != "") { $client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build(); $params = [ 'index' => 'goods', 'type' => '_doc', 'body' => [ 'query' => [ 'match' => ['name' => $search ] ], 'highlight' => [ 'fields' => ['name' => [ 'pre_tags' => "", 'post_tags' => "",] ] ] ] ];// dd($params); // 执行搜索 $response = $client->search($params);// dd($response); //高亮 $data = $response['hits']['hits']; $res = []; //循环获取高亮字段 foreach ($data as $v) { if (!empty($v['highlight']['name'][0])) { $v['_source']['name'] = $v['highlight']['name'][0]; } array_push($res, $v['_source']); }// 热词 Redis::zincrby('search', 1, $search); return $res; } $res = Goods::get();// dd($res); return $res;
基本实现
来源地址:https://blog.csdn.net/NobleCharacter/article/details/126608094