laravel8使用es完成微信小程序高亮搜索

 

wxml:

<l-search-bar placeholder="搜索" custom bind:linblur="search">

    <view name="icon"/>
  </l-search-bar>

 <!-- <rich-text nodes="{{item.title}}"></rich-text> -->
    <l-card type="primary" wx:for="{{search}}"
    
            image="{{item.image}}"
            title="{{item.title}}">
        <view class="content">
             <view>{{item.text}}</view>
             <view>作者:{{item.author}}</view>
        </view>
    </l-card>

js:

Page({

  /**
   * 页面的初始数据
   */
  data: {
    search:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  search(e){
    console.log(e)
    var title = e.detail.value
    var that = this
     wx.request({
      url: 'http://www.three.exam.com/api/search',
      data: {
        title:title
      },
      header: {
        token:wx.getStorageSync('token')
      },
      success (res) {
        console.log(res.data)
        that.setData({
          search:res.data.data
        })
      }
    })
  },
})

引入卡片 Card | Lin UI

json:

{
  "usingComponents": {
    "l-search-bar":"/miniprogram_npm/lin-ui/search-bar",
    "l-card":"/miniprogram_npm/lin-ui/card"
  }
}

php:

1.下载laravel8 支持的es插件 

composer require elasticsearch/elasticsearch

2.在要使用的地方引入ES

use Elasticsearch\ClientBuilder;

3.生成ES对象

$client = ClientBuilder::create()‐>setHosts('连接地址')‐>build();

具体代码:

  /**
     * 添加索引
     */
    public function create($results)
    {
        $client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();

        if (!empty($results)){
            $data=[
                'id' => $results[0]['id'],
                'title' => $results[0]['title'],
                'image'=>$results[0]['image'],
                'author' => $results[0]['author'],
                'text'=>$results[0]['text']
            ];
        }else{
            $data=[
                'id' => 3,
                'title' => '我们的婚姻',
                'image'=>'https://img1.baidu.com/it/u=3834462090,3152406810&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=745',
                'author' => 'XXXX',
                'text'=>'把持都把持不住!'
            ];
        }

        //拼接数据
        $params = [
            'index' => 'article',
            'type' => '_doc',
            'id' => $data['id'],
            'body' => $data
        ];
        //存储到es中
        $response = $client->index($params);
        return $response;
    }
    /**
     * 文章展示
     */
    public function showArticle()
    {
        $data = Article::orderBy('id','desc')->get();
        return ['code'=>200,'msg'=>'展示成功','data'=>$data];
    }
    /**
     * 文章搜索
     */
    public function selectArticle(request $request)
    {

        $title = $request->get('title');
        $client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
        $params = [
            'index' => 'article',
            'type' => '_doc',
            'body' => [
                'query' => [
                    'match' => [
                        'title'=>[
                            'query' => $title
                        ]
                    ]
                ],
                'highlight'=>[
                    'fields'=>[
                        'title'=>[
                            'pre_tags'=>[
                                '<span style="color: red">'
                            ],
                            'post_tags'=>[
                                '</span>'
                            ]
                        ]
                    ]
                ]
            ]
        ];

            $results = $client->search($params);
        //如果es里有数据 走es高亮显示
        if ($results['hits']['hits']){
            foreach ($results['hits']['hits'] as $key => $item)
            {
                $results['hits']['hits'][$key]['_source']['title'] = $item['highlight']['title'][$key];
            }
            $results = array_column($results['hits']['hits'], '_source');
            return ['code'=>200,'msg'=>'es搜索成功','data'=>$results];
        }else{
            //没有数据就查询数据库然后再把数据添加到es索引中
            $where= [];
            $where[] = ['title','like',"$title"];
            $results = Article::where($where)->get()->toArray();
            //调用添加es方法
            $this->create($results);
            return ['code'=>200,'msg'=>'搜索成功','data'=>$results];
        }
    }
  /**
     * 修改
     * @return array|callable
     */
    public function upArticle()
    {
        $client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
        //测试数据
        $data=[
            'id' => 3,
            'title' => '我们的婚姻',
            'image'=>'https://img1.baidu.com/it/u=3834462090,3152406810&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=745',
            'author' => 'XXXX',
            'text'=>'把持都把持不住!'
        ];
        $params = [
            'index' => 'article',
            'type' => '_doc',
            'id' => $data['id'],
            'body' => [
                'title' => $data['title'],
                'image' => $data['image'],
                'author' => $data['author'],
                'text'=> $data['text']
            ],
        ];
        $response = $client->index($params);
        return $response;

    }
  /**
     * 删除
     */
    public function deleteArticle()
    {
        $client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
        //测试数据
        $data=[
            'id' => 1,
            'title' => '红海行动',
            'image'=>'https://img0.baidu.com/it/u=352533610,629194150&fm=253&fmt=auto&app=138&f=JPEG?w=334&h=500',
            'author' => 'ssss',
            'text'=>'真人版吃鸡!'
        ];
        $params = [
            'index' => 'article',
            'type' => '_doc',
            'id' => $data['id'],
        ];
        $response = $client->delete($params);
        return $response;
    }

注意一定要先开起 elasticsearch 我用的es 6.5.3版本 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值