composer require elasticsearch/elasticsearch
es入口
namespace App\Http\Es;
use Elasticsearch\ClientBuilder;
class EsService
{
private static $EsClient = false;
private function __construct()
{
}
public static function getIntance()
{
if (self::$EsClient === false) {
self::$EsClient = ClientBuilder::create()->build();
}
return self::$EsClient;
}
}
//
use Elasticsearch\ClientBuilder;
use App\Http\Es\EsService;
public function esCreate()
{
$client = ClientBuilder::create()->build();
$params = [
'index' => 'area',//自定义index(库名)
'body' => [
'settings' => [
'number_of_shards' => 3,
'number_of_replicas' => 2
],
'mappings' => [
'_source' => [
'enabled' => true
],
'properties' => [
'area' => [
'type' => 'text',
"analyzer" => "ik_max_word",
"search_analyzer" => "ik_max_word"
]
]
]
]
];
//执行创建
$res = $client->indices()->create($params);
dd($res);
}
public function esAdd()
{
$data = Shop::all()->toArray();//获取到数据
$client =EsController::getIntance();
foreach ($data as $k=>$v){
$params = [
'index' =>'area',//上面的自定义index
'type' =>'_doc',//表(固定的写法)
'id' => $v['id'],//主键
'body' =>$v//数据
];
$res = $client->index($params);
}
dd($res);
}
public function esSearch(Request $request)
{
$search_field = 'area';
$word =$request->get('word');//接收关键字
$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' => 'area',//自定义的index
'body' => $body,
];
$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');
$data = array_column($results['hits']['hits'],'_source');
return response()->json(['code'=>200,'msg'=>'ok','data'=>$data]);
}
版权声明:本文为Lorientasn原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。