http://localhost:9200/
运行目录下的elasticsearch.bat
出现started进入http://localhost:9200/
首先单例模式封装es连接
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;
}
Es控制器
static $es;
static $search_filed=['comment','create_at'];
static $index="user";
/**
* es索引创建
*/
public function esCreate()
{
$client = EsController::getIntance();;
$search_filed=self::$search_filed;
$properties=[];
foreach ($search_filed as $k=>$v){//中文分词器配置
$properties[$v]=[
'type' =>"text", //这是一种搜索的格式 自己可以了解一下参数
"analyzer" => "ik_max_word",
"search_analyzer" => "ik_max_word"
];
}
$params = [
'index' => self::$index,//类似于库名
'body' => [
//这里是权重值 你自己根据需求加入
'settings' => [
'number_of_shards' => 3,
'number_of_replicas' => 2
],
'mappings' => [
'_source' => [
'enabled' => true
],
'properties' =>$properties
]
]
];
//执行创建
$r = $client->indices()->create($params);
}
/**
* @throws \think\exception\DbException
* es数据添加
* ++待批量入++
*/
public function esAdd()
{
$client = EsController::getIntance();;
$data = json_decode(json_encode(Comment::all()), true);
foreach ($data as $k => $v) {
$params = [
'index' => self::$es,//你上面创建的库
'type' => '_doc',//表(额外需要注意的,这里是固定的写法)
'id' => $v['id'],//主键
'body' => $v//数据
];
$r = $client->index($params);
}
}
/**
* @param Request $request
* @return \think\response\Json
* es搜素多字段搜索
*/
public function esSearch(Request $request)
{
$client = EsController::getIntance();;
$word = $request->get('word');//接收关键字
$search_filed=self::$search_filed;
if(empty($word)){
$body=[];
}else{
$fields=[];
$should=[];
foreach ($search_filed as $k=>$v){
$fields[]=[$v=>new \stdClass()];
$should[]=['match' => [$v => $word]];
}
$body=[
'query' => [
//bool 关键字: 用来组合多个条件实现复杂查询
'bool' => [
//bool 查询如果不加 should 就是多个字段必须全部填写 才能查询 should: 相当于|| 成立一个就行
"should" =>$should
]
],
'highlight' => [//高亮
'pre_tags' => ["<em style='color: red'>"],//样式自己写
'post_tags' => ["</em>"],
'fields' =>$fields
]
];
}
$params = [
'index' => self::$index,//索引(跟上面你填写的数据库一样)
//'type' => '_doc',
'body' =>$body
];
$results = $client->search($params);//es搜索
if (!empty($word)){
foreach ($results['hits']['hits'] as $k => $v) {
//判断 对应的字段是否为空 如果不为空 就进行一个赋值 然后进行搜索
foreach ($search_filed as $kk=>$vv){
if (!empty($v['highlight'][$vv][0])) {
$results['hits']['hits'][$k]['_source'][$vv] = $v['highlight'][$vv][0];
}
}
}
}
// 这里 array_column 取出数组的某一列 数据都在 _source 里面
$data = array_column($results['hits']['hits'], '_source');
return $data;
}