laravel Es搜索 检索高亮显示

**安装教程,网上都可以查询到。这里只简单文字介绍,详细步骤可私信我**
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>
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 7
        Mail::raw("注册成功", function ($message) {
            $message->subject('注册');
            $message->to('7@qq.com');
        });
        if (count(Mail::failures())) {
            return '发送失败';
        }
2年前 评论
    public function goodsAdd(CheckGoodsAdd $request)
    {
        $data = $request->except(['_token', 'file']);
        DB::beginTransaction();
        try {
            $arr = explode(',', $data['img']);
            $img = array_filter($arr);
            $data['img'] = implode(',', $img);
            $res = Goods::goodsAdd($data);
            if (!$res) {
                return redirect('goodsAddShow');
            }
            $id = $res->id;
            $result = $res->toArray();
            $es = new Es();
            $es_res = $es->add_doc($id, $result, 'fresh', 'goods');
            if ($es_res) {
                DB::commit();
                return redirect('goodsList');
            }
        } catch (Exception $exception) {
            DB::rollBack();
            return redirect('goodsAddShow');
        }
    }
2年前 评论

修改

    public function goodsUpdate(CheckGoodsAdd $request)
    {
        $data = $request->except(['_token', 'file']);
//        开启事务
        DB::beginTransaction();
        try {
//        将字符串分割为数组
            $arr = explode(',', $data['img']);
//        过滤空数组
            $img = array_filter($arr);
//        数组转化为字符串
            $data['img'] = implode(',', $img);
            $res = Goods::goodsUpdate($data);
            if (!$res) {
                return redirect('goodsUpdateShow');
            }
            $id = $data['id'];
            $result = $data;
            $es = new Es();
            $es_res = $es->update_doc($id, $result, 'fresh', 'goods');
            if ($es_res) {
                DB::commit();
                return redirect('goodsList');
            }
            return redirect('goodsList');
        } catch (Exception $exception) {
            DB::rollBack();
            return redirect('goodsAddShow');
        }
    }
2年前 评论

封装es

<?php
namespace App\lib;

use Elasticsearch\ClientBuilder;

class Es
{
    //ES客户端链接
    private $client;

    /**
     * 构造函数
     * MyElasticsearch constructor.
     */
    public function __construct()
    {
        $params = array(
            '127.0.0.1:9200'
        );
        $this->client = ClientBuilder::create()->setHosts($params)->build();
    }

    /**
     * 判断索引是否存在
     * @param string $index_name
     * @return bool|mixed|string
     */
    public function exists_index($index_name = 'test_ik')
    {
        $params = [
            'index' => $index_name
        ];

        try {
            return $this->client->indices()->exists($params);
        } catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
            $msg = $e->getMessage();
            $msg = json_decode($msg,true);
            return $msg;
        }
    }

    /**
     * 创建索引
     * @param string $index_name
     * @return array|mixed|string
     */
    public function create_index($index_name = 'test_ik') { // 只能创建一次
        $params = [
            'index' => $index_name,
            'body' => [
                'settings' => [
                    'number_of_shards' => 5,
                    'number_of_replicas' => 0
                ]
            ]
        ];

        try {
            return $this->client->indices()->create($params);
        } catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
            $msg = $e->getMessage();
            $msg = json_decode($msg,true);
            return $msg;
        }
    }

    /**
     * 删除索引
     * @param string $index_name
     * @return array
     */
    public function delete_index($index_name = 'test_ik') {
        $params = ['index' => $index_name];
        $response = $this->client->indices()->delete($params);
        return $response;
    }

    /**
     * 添加文档
     * @param $id
     * @param $doc ['id'=>100, 'title'=>'phone']
     * @param string $index_name
     * @param string $type_name
     * @return array
     */
    public function add_doc($id,$doc,$index_name = 'test_ik',$type_name = 'goods') {
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id,
            'body' => $doc
        ];

        $response = $this->client->index($params);
        return $response;
    }

    /**
     * 判断文档存在
     * @param int $id
     * @param string $index_name
     * @param string $type_name
     * @return array|bool
     */
    public function exists_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods') {
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id
        ];

        $response = $this->client->exists($params);
        return $response;
    }

    /**
     * 获取文档
     * @param int $id
     * @param string $index_name
     * @param string $type_name
     * @return array
     */
    public function get_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods') {
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id
        ];

        $response = $this->client->get($params);
        return $response;
    }

    /**
     * 更新文档
     * @param int $id
     * @param string $index_name
     * @param string $type_name
     * @param array $body ['doc' => ['title' => '苹果手机iPhoneX']]
     * @return array
     */
    public function update_doc($id, $body=[],$index_name = 'test_ik',$type_name = 'goods') {
        // 可以灵活添加新字段,最好不要乱添加
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id,
            'body' => $body
        ];

        $response = $this->client->index($params);
        return $response;
    }

    /**
     * 删除文档
     * @param int $id
     * @param string $index_name
     * @param string $type_name
     * @return array
     */
    public function delete_doc($id = 1,$index_name = 'test_ik',$type_name = 'goods') {
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id
        ];

        $response = $this->client->delete($params);
        return $response;
    }

    /**
     * 搜索文档 (分页,排序,权重,过滤)
     * @param string $index_name
     * @param string $type_name
     * @param array $body
     * $body = [
    'query' => [
    'bool' => [
    'should' => [
    [
    'match' => [
    'cate_name' => [
    'query' => $keywords,
    'boost' => 4, // 权重大
    ]
    ]
    ],
    [
    'match' => [
    'goods_name' => [
    'query' => $keywords,
    'boost' => 3,
    ]
    ]
    ],
    [
    'match' => [
    'goods_introduce' => [
    'query' => $keywords,
    'boost' => 2,
    ]
    ]
    ]
    ],
    ],
    ],
    'sort' => ['id'=>['order'=>'desc']],
    'from' => $from,
    'size' => $size
    ];
     * @return array
     */
    public function search_doc($index_name = "test_ik",$type_name = "goods",$body=[]) {
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'body' => $body
        ];

        $results = $this->client->search($params);
        return $results;
    }
}
2年前 评论

封装es搜索

<?php


namespace App\lib;



use App\Models\Goods;

class Search
{
    public function search($keywords){

//        $fangName =$request->get('fangName');
        if (!empty($keywords)) {
            $es = new Es();
            $body = [
                'query' => [
                    'match' => [
                        'name' => [
                            'query' => $keywords
                        ]
                    ]
                ],
                'highlight'=>[
                    'fields'=>[
                        'name'=>[
                            'pre_tags'=>[
                                '<span style="color: #ff0000">'
                            ],
                            'post_tags'=>[
                                '</span>'
                            ]
                        ]
                    ]
                ]
            ];
            $res = $es->search_doc('fresh', 'goods', $body);
            $data = array_column($res['hits']['hits'], '_source');
            foreach ($data as $key=>&$v){
                $v['name'] = $res['hits']['hits'][$key]['highlight']['name'][0];
            }
            unset($v);
            return $data;
        }
        $data = Goods::all();

        return $data;
    }
}
2年前 评论

搜索调用

    public function search(Request $request){
        $keywords=$request->get('keywords');
        $es=new Search();
        $es_search=$es->search($keywords);
        return $es_search;
    }
2年前 评论

搜索

<searchHaveHistory id="history"
    bind:searchEvent="searchEvent">
</searchHaveHistory>
<rich-text nodes="{{item.name}}"></rich-text>
 searchEvent(e){
    // console.log("用户搜索"+e.detail)
    let keywords=e.detail
    let that = this;
    // 判断token是否存在
    var token = wx.getStorageSync('token')
    //  判断是否登录过
    var id = wx.getStorageSync('id')
    let header = { 'Authorization': 'Bearer' + " " + token }
  // 实例化
  var promise = new Promise(function (resolve) {
    // 调用请求
    resolve(http("goods/search", 'get', {keywords}, header));
  });
  // 取出请求里的值
  promise.then(function (res) {
    console.log(res)
  that.setData({
      movies:res
    })
    setTimeout(()=>{
      wx.hideLoading();
    },1000)
  }).catch(function (error) {
    console.error(error);
  }); 
  },
   public static function bookList($keywords){
        return self::when($keywords, function ($query) use ($keywords) {
            $query->where('title', 'like', "%$keywords%");
        })->get();
    }
   <td>@if(!empty($keywords))
                            @php
                                $keywords=$_REQUEST['keywords'];
                                echo str_replace($keywords,"<font color='red'>$keywords</font>",$val->name)
                            @endphp
                        @else
                            {{$val->name}}
                        @endif
                    </td>
2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!