laravel 结合ElasticSearch高亮显示

该博客介绍了如何在PHP中使用Elasticsearch客户端库创建索引,设置分析器,以及处理事件来实时更新索引。在创建文章时,数据会被添加到Elasticsearch索引中,同时提供了搜索功能,支持高亮显示搜索结果的关键内容。整个流程涵盖了从数据插入到检索的完整过程。
摘要由CSDN通过智能技术生成

安装

composer require elasticsearch/elasticsearch

创建索引

 private  $client;
    public function __construct()
    {
        $this->client = ClientBuilder::create(['127.0.0.1:9200'])->build();
    }

    //创建索引
    public function createindex()
    {
        $params = [
            'index' => 'article',
            'body' => [
                'mappings' => [
                    '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 = $this->client->indices()->create($params);
        var_dump($response);
    }

生成事件
在这里插入图片描述

php artisan event:generate
<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class Article
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $table;
    public $data;
    public $id;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($table,$data,$id)
    {
        //
        $this->table=$table;
        $this->data=$data;
        $this->id=$id;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

<?php

namespace App\Listeners;

use App\Events\Article;
use Elasticsearch\ClientBuilder;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class ArticleListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Article  $event
     * @return void
     */
    public function handle(Article $event)
    {
        $client = ClientBuilder::create(['127.0.0.1:9200'])->build();

        $params = [
            'index' => $event->table,
            'type' => '_doc',
            'id' => $event->id,
            'body' => $event->data
        ];
        // 添加数据到索引文档中
        $response=$client->index($params);
        return $response;
    }
}

添加数据

    public function create(Request $request)
    {
        if ($request->isMethod('post')){

            $validator = \Validator::make($request->all(), [
                'title' => 'required',
                'content' => 'required',
            ],[
                'title.required'=>'标题必填',
                'content.required'=>'内容必填',
            ]);

            if ($validator->fails()) {
                return redirect('/articles/create')
                    ->withErrors($validator)
                    ->withInput();
            }
            $data=$request->post();
            $id=DB::table('article')->insertGetId($data);
            if($id){
                //索引添加数据  事件
                Event::dispatch(new Article('article',$data,$id));
                return ['code'=>200,'msg'=>'添加成功','data'=>$data];
            }
            return ['code'=>400,'msg'=>'失败','result'=>null];
        }
        return view('article/create');
    }

搜索高亮显示

    //搜索
    public function index(Request $request){
        $searchKey=$request->get('searchKey');
        if ($searchKey){
            $params = [
                'index' => 'article',
                'body' => [
                    'query' => [
                        'multi_match' => [
                            "query"=> $searchKey,
                            "fields"=> [ "title", "content" ],
                        ]
                    ],
                    'highlight' => array(
                        "pre_tags"=> ["<span style='color:red'>"],
                        "post_tags"=>["</span>"],
                        'fields' => array(
                            '*' => new Highlighter(),
                        )
                    )
                ]
            ];
            $response = $this->client->search($params);
            if ($response['hits']['total']['value'] > 0 ){
                foreach ($response['hits']['hits'] as $v){
                    $data=$v['highlight'];

                }
            }

            return ['code'=>200,'msg'=>'获取成功','data'=>$data];

        }else{
           $arr= DB::table('article')->get();
            return ['code'=>200,'msg'=>'获取成功','data'=>$arr];
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值