1.自行选择版本下载
2.把下载好的ik包改名ik放到 elasticsearch-7.10.1\plugins\ik
3.运行访问:9200
4.在运行kibana.bat 、本地域名加:5601,进入点击管理、进去数据管理里面的索引管理你创建的es仓库就可以看见了
1.安装composer扩展 下面代码块根据自己需求微做修改就好
composer require elasticsearch/elasticsearch
2.单例模式实现elasticsearch连接
<?php
namespace App\Http\Controllers;
use Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;
class EsController extends Controller
{//私有的静态属性
private static $EsClient = false;
//私有的构造方法
private function __construct()
{
}
//3.私有的克隆方法
private function __clone()
{
}
//公有的静态方法
public static function getIntance()
{
if (self::$EsClient == false) {
self::$EsClient = ClientBuilder::create()->build();
}
return self::$EsClient;
}
}
3.创建索引(带有分词器)
public function escreate(){
$params = [
'index' => 'task'//库名
];
// Create the index
$client = ClientBuilder::create()->build();
$response = $client->indices()->create($params);
//指定分词
$client = ClientBuilder::create()->build();
$params = [
'index' => 'goods',
'body' => [
'settings' => [
'number_of_shards' => 3,
'number_of_replicas' => 2
],
'mappings' => [
'_source' => [
'enabled' => true
],
'properties' => [
'name' => [
'type' => 'text',
"analyzer" => "ik_max_word",
"search_analyzer" => "ik_max_word"
],
'desc' => [
'type' => 'text',
"analyzer" => "ik_max_word",
"search_analyzer" => "ik_max_word"
]
]
]
]
];
// Create the index with mappings and settings now
$response = $client->indices()->create($params);
}
4.批量添加数据
public function addition()
{
$client =EsController::getIntance();
$body=[];
for($i = 1; $i <= 30; $i ++) {
$params['body'][]=array(
'index' => array(
'_index'=> "paopao",
'_type'=> 'test'
),
);
$params['body'][]=array(
'id'=>$i,
'aa'=>"aa$i",
"kk"=>"kk$i"
);
}
$response = $client->bulk($params);
print_r($response);
}
5.分页搜索高亮显示
public function essearch(){
$search_field="pid_path_name";//搜索的字段
$word = input('word','');//接收关键字
$page = input('page',1);//接收当前页(如果没接收到,默认是1)
$size = input('size',5);;//每页显示条数
$limit = ($page-1)*$size;//偏移量
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();//创建es实例
//设置查询的条件
if (empty($word)){
$body=[
];
}else{
$body=[
//查询内容
'query' => [
'match' => [//匹配
$search_field => $word//匹配字段
]
],
'highlight' => [//高亮
'pre_tags' => ["<em style='color: red'>"],//样式自己写
'post_tags' => ["</em>"],
'fields' => [
$search_field => new \stdClass()
]
]
];
}
$params = [
'index' => 'task',//索引(类似于库)
'body' => $body,
'size'=>$size,//每页显示条数
'from'=>$limit//偏移量
];
$results = $client->search($params);//es搜索
if (!empty($word)){
foreach ($results['hits']['hits'] as $k=>$v){
$results['hits']['hits'][$k]['_source'][$search_field] = $v['highlight'][$search_field][0];
}
}
$data = array_column($results['hits']['hits'],'_source');
$arr['page'] = $page;//当前页
$arr['total'] = $results['hits']['total']['value'];//总条数
$arr['last_page'] = ceil($results['hits']['total']['value']/$size);//总页数
$arr['data'] = $data;//数据
return json($arr);
}