thinkph5.1 + es

19 篇文章 0 订阅

核心代码

<?php
/**
 * Created by.
 * User: Jim
 * Date: 2020/11/11
 * Time: 12:18
 */

namespace app\lib\search;


use Elasticsearch\ClientBuilder;
use think\Controller;
use think\Db;

/**
 * elasticsearch 产品搜索
 * Class Es
 * @package app\lib\search
 */
class Es extends Controller
{

    static $instance = null;

    static $index_es = 'goods_es';
    static $type_es = 'goods_es';

    static $prefix = 'goods_';

    private $client = null;


    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $params = [
            '127.0.0.1:9200',
        ];


        $this->client = ClientBuilder::create()->setHosts($params)->build();



    }

    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    public static function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new self;
        }
        return self::$instance;
    }


    /**
     * 功能:生成索引
     */
    public function index()
    {

        set_time_limit(0);
        /**
         * 添加 删除 修改的时候 都进行更新索引值
         */
        $where['is_del'] = 0;
        $where['for_au'] = 1;
        $lists = Db::name('goods')
            ->where($where)
            ->field('id,product_code title,product_name content')
            ->select();


        foreach ($lists as $row) {
            $params = [
                'body' => [
                    'id' => $row['id'],
                    'title' => $row['title'],
                    'content' => $row['content']
                ],
                'id' => 'goods_' . $row['id'],
                'index' => self::$index_es,
                'type' => self::$type_es
            ];
            $this->client->index($params);
        }

        echo 'create index success';

    }

    /**
     * 获取索引
     */
    public function getIndex($name = '')
    {
        try {
            $params = [
                'index' => self::$index_es,
                'type' => self::$type_es,
                'id' => self::$prefix . $name,
            ];
            $res = $this->client->get($params);
            return $res;
        } catch (\Exception $e) {
            echo $e->getMessage();
        }


    }


    /**
     * 更新索引
     */
    public function updateIndex($id, $data = [])
    {
        // 每次更新数据的时候   只要for_au == 1 然后更新数据就OK
        if (empty($id) || empty($data)) {
            return false;
        }
        $data = [
            'index' => self::$index_es,
            'type' => self::$type_es,
            'id' => $id,
            'body' => [
                'doc' => $data //这里的data是个一维关联数组,和常用的ORM更新方法参数一致。
            ]
        ];

        try {
            $res = $this->client->update($data);
            return $res['result'];
        } catch (\Exception $e) {
            return false;
        }

    }


    /**
     * 从索引中删除文档
     * @param string $name
     * @return bool
     */
    public function delIndex($name = '')
    {

        $params = [
            'index' => self::$index_es,
            'type' => self::$type_es,
            'id' => self::$prefix . $name,
        ];

        try {
            $res = $this->client->delete($params);
            return true;
        } catch (\Exception $e) {
            return '';
        }


    }


    /**
     * 查询
     * 返回的时候goods查询的sql 语句
     * return String `goods_id in (1,2,3,4)`  or ''
     */
    public function search($keyword = '')
    {
        $keyword = trim($keyword);
        if (!$keyword) return '';

        $params = [
            'index' => self::$index_es,
            'type' => self::$type_es,
            'size' => 1000,
            'body' => [
                'query' => [

                    'bool' => [
                        'should' => [
                            ['match' => ['title' => ['query' => $keyword, 'fuzziness' => 'AUTO', 'operator' => 'or',]]],
                            ['match' => ['content' => ['query' => $keyword, 'fuzziness' => 'AUTO', 'operator' => 'or',]]],
                        ]
                    ]

                ]
            ]
        ];

        try {

            $res = $this->client->search($params);
            $goods = $res['hits']['hits'];
            $goods = array_column($goods, '_source');
            $goods = array_column($goods, 'id');

            $ids_str = implode(',',$goods);
            if ($ids_str == '') return '';
            // id in (1,2,4,5);
            return "goods.id in ({$ids_str})";
        } catch (\Exception $e) {
            return '';

        }


    }

}

使用

 // es 搜索
  $es_where = '';
  try {
      $es_where = Es::getInstance()->search($keyword);
  } catch (\Exception $e) {
  }
  
  // goods_id in (1,2,3,4,5);
  dump($es_where);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值