laravel Es搜索 检索高亮显示

Laravel框架
416
0
0
2022-09-12
标签   Elasticsearch

**安装教程,网上都可以查询到。这里只简单文字介绍,详细步骤可私信我**

1.下载安装JDK

下载地址https://www.oracle.com/technetwork/java/javase/downloads/index.html

2.配置 JAVA_HOME环境变量

3.打开命令行窗口,输入java -version查看JDK版本 出现版本号 安装成功

4.下载安装elasticsearch

下载地址https://www.elastic.co/downloads

5.配置Path环境变量

*6.打开命令行窗口 执行命令 elasticsearch -d 启动elasticsearch*

7.浏览器打开 http://localhost:9200 出现详细信息 安装成功

8.安装Elasticsearch-Head

elasticsearch-head是一个用于浏览ElasticSearch集群并与其进行交互的Web项目

GitHub托管地址:https://github.com/mobz/elasticsearch-head下载并解压:

9.使用cnpm安装,这样速度会快一些 cnpm的安装方法:

npm install -g cnpm --registry=https://registry.npm.taobao.org

*10.npm run start 启动成功后,可通过http://localhost:9100进行访问*

11.由于跨域(Elasticsearch位于9200端口),需要添加配置: E:\elasticsearch-7.1.0\config\elasticsearch.yml中

#新添加的配置行
http.cors.enabled: true
http.cors.allow-origin: "*"

1.首先我们要先连接Es

<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Elasticsearch\ClientBuilder;

class Text extends Controller
{
    //受保护的:只能自己和自己的子类调用   
    protected $es;

    //构造函数的作用:实例化类的时候自动调用,执行每个方法前都会自动执行一次   
    public function __construct()
    {
        //连接es   
        $this->es = ClientBuilder::create()->setHosts(['localhost:9200'])->build();
    }

    //创建索引(类似于创建数据库)   
    public function createIndex(){
        //设置参数   
        //index表示索引名称,类似于数据库名称   
        $params = [
            'index'=>'zg4',
            'body'=>[
                'mappings'=>[
                    'properties'=>[//汇总字段的   
                        'title'=>[
                            'type'=>'text',
                            "analyzer" => "ik_max_word",
                            "search_analyzer" => "ik_max_word"
                        ]
                    ]
                ]
            ]
        ];
        $this->es->indices()->create($params);
    }


    //添加文档(给数据库的某张数据表添加数据)   
    public function addDoc(){
        $params = [
            'index'=>'zg3',//类似于数据库名称   
            'type'=>'article',//类似于数据表名称(不需要创建的,直接指定就可以了)   
            'id'=>1,//当前要添加的数据的主键id(自己指定的)   
            'body'=>['id'=>1,'name'=>'zhangsan','sex'=>1]//数据
        ];
        $res = $this->es->index($params);
        dump($res);
    }

    //修改文档(给数据库的某张表修改数据)   
    public function updateDoc(){
        $params = [
            'index'=>'zg3',
            'type'=>'article',
            'id'=>1,
            'body'=>[
                //修改的内容   
                'doc'=>['name'=>'张三']
            ]
        ];

        $res = $this->es->update($params);
        dump($res);
    }

    //删除文档(根据id删除某个数据库下的某张表下的内容)   
    public function deleteDoc(){
        try {
            $params = [
                'index'=>'zg3',
                'type'=>'article',
                'id'=>1
            ];
            $this->es->delete($params);
            return json(['code'=>0,'msg'=>'删除成功']);
        }catch (\Exception $e){
            return json(['code'=>1,'msg'=>'删除失败']);
        }
    }

    //批量添加文档   
    public function addDocAll(){
        $data = Article::select();
        $data = collection($data)->toArray();
        foreach ($data as $k=>$v){
            $params = [
                'index'=>'zg4',//类似于数据库名称   
                'type'=>'_doc',//类似于数据表名称(不需要创建的,直接指定就可以了)   
                'id'=>$v['id'],//当前要添加的数据的主键id(自己指定的)   
                'body'=>$v//数据
            ];
            $res = $this->es->index($params);
        }
    }

    //es搜索   
    public function esSearch(Request $request)
    {
        $word = $request->get('keyName');
        if (empty($word)) {
            $data = Housing::with(['HouOtt', 'HouPay', 'HouSet', 'HouType'])->get()->toArray();
            return response()->json(['code' => 1, 'msg' => 'word参数不能为空', 'data' => $data]);
        }
        $page = $request->get('page', 1);//接收当前页,默认值是1   
        $size = config('pagesize');//每页显示条数   
        $from = ($page - 1) * $size;//偏移量   
        $params = [
            'index' => 'index',
            'body' => [
                //执行   
                'query' => [
                    //匹配   
                    'match' => [
                        'f_name' => $word
                    ]
                ],
                'highlight' => [
                    'pre_tags' => ["<span style='color: red'>"],
                    'post_tags' => ['</span>'],
                    'fields' => [
                        'f_name' => new \stdClass()
                    ]
                ]
            ],
            'size' => $size,//每页显示的条数   
            'from' => $from//偏移量
        ];
        $res = $this->es->search($params);
        $data = $res['hits']['hits'];
        foreach ($data as $k => $v) {
            $data[$k]['_source']['f_name'] = $v['highlight']['f_name'][0];
        }
        $data = array_column($data, '_source');
        return response()->json(['code' => 0, 'msg' => '成功', 'data' => $data]);
    }
}

——-更新——

框架安装:composer require elasticsearch/elasticsearch

elasticsearch -d 启动elasticsearch/bin/elasticsearch.bat 9200

命令行 切换到head 执行npm run start

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
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;
    }

    public function escreate()
    {
        $params = [
            'index' => 'gao1103s'//库名
        ];
        // Create the index   
        $client = ClientBuilder::create()->build();
        $response = $client->indices()->create($params);
        //指定分词   
        $client = ClientBuilder::create()->build();
        $params = [
            'index' => 'gao1103s',
            '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);
    }

    public function addition()
    {
        $client = ClientBuilder::create()->build();
        $data = WechatShop::all();
        $body = [];
        foreach ($data as $v) {
            $params['body'][] = array(
                'index' => array(
                    '_index' => "gao1103s",
                    '_type' => 'text'
                ),
            );

            $params['body'][] = array(
                'id' => $v['id'],
                'shop_name' => $v['shop_name'],
                'shop_img' => $v['shop_img'],
                'shop_price' => $v['shop_price'],
            );
        }
        $response = $client->bulk($params);
        print_r($response);
    }

    public function essearch(Request $request)
    {
        $search_field = "shop_name";//搜索的字段   
        $word = $request->input('word', '');//接收关键字   
        $page = $request->input('page', 1);//接收当前页(如果没接收到,默认是1)   
        $size = $request->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' => 'gao1103s',//索引(类似于库)   
            '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 response()->json($arr);
    }

}

小程序页面不解析

<rich-text nodes="{{item.f_name}}"></rich-text>