下载ES-PHP类库

vim composer.json
# 添加
{
    "require":{
        "elasticsearch/elasticsearch":"^7.0"
    }
}
# 更新/下载
composer update

Yaconf配置文件

cd ~/Site/ini
touch es_video.ini
vim es_video.ini
// 添加配置如下
# ElasticSearch 配置
host='127.0.0.1'
port=8101

底层代码

app\lib下创建ES\EsClient.php

<?php
/**
 * Created by PhpStorm.
 * User: qvbilam
 * Date: 2019-06-16
 * Time: 00:28
 */

namespace App\Lib\ES;
// 使用单例模式
use EasySwoole\Component\Singleton;
// 使用ElasticSearch-php类库
use Elasticsearch\ClientBuilder;

class EsClient
{
    use Singleton;
    public $client = null;

    private function __construct()
    {
        $config = \Yaconf::get('es_video');
        $host = $config['host'];
        $port = $config['port'];
        try {
            // 链接ElasticSearch
            $this->client = ClientBuilder::create()
                ->setHosts(["$host:$port"])
                ->build();
        } catch (\Exception $e) {
            // todo 写日志,发送报警
        }
        if (empty($this->client)) {
            // todo 写日志,发送报警
        }
    }

    public function __call($name, $arguments)
    {
        return $this->client->$name(...$arguments);
    }

}

解读

关于...$arguments.我们请求不存在的方法search([1,2,3])的时候,$name=search...$arguments会输出

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

就相当于我们调用Class->search([1,2,3]).所以...$arguments等同于$arguments[0],$arguments[1],$arguments[2].一定要学会运用哦~加油!

注入DI容器

EasySwooleEvent.php中添加

use App\Lib\ES\EsClient;

mainServerCreate()方法中添加

/*Di注入ElasticSearch*/
Di::getInstance()->set('ES',EsClient::getInstance());

App\HttpController\Test.php中创建测试demo

use EasySwoole\Component\Di;
...
public function estest()
{
    # 请求参数
    $params = [
        "index" => "small_video",
        "type" => "_doc",
        'body' => [
            'query' => [
                'multi_match' => [
                    'query' => '二了',
                    'fields' => ['name','content']
                ]
            ]
        ]
    ];
    $client = Di::getInstance()->get('ES');
    $result = $client->search($params);
    $this->writeJson(200,'ok',$result);
}

重启EeaySwoole服务访问test/estest

Model层封装

App\Model创建ES\EsVideo.php

<?php
/**
 * Created by PhpStorm.
 * User: qvbilam
 * Date: 2019-06-16
 * Time: 01:44
 */

namespace App\Model\ES;

use EasySwoole\Component\Di;

class EsVideo
{
    // 指定索引
    static public $index = 'small_video';
    // 指定类型
    static public $type = '_doc';
    // 默认查询字段
    static public $default_video_fields = ['name', 'content'];

    // 搜索视频名/内容
    static public function searchByVideo($search, $fields = [])
    {
        $search = trim($search);
        if (empty($search)) {
            return [];
        }
        if (empty($fields)) {
            $fields = self::$default_video_fields;
        }
        $params = [
            "index" => self::$index,
            "type" => self::$type,
            'body' => [
                'query' => [
                    'multi_match' => [
                        'query' => $search,
                        'fields' => $fields
                    ]
                ]
            ]
        ];
        $client = Di::getInstance()->get('ES');
        $result = $client->search($params);
        return $result;
    }
}

测试
App\HttpController\Test.php添加测试方法

use App\Model\ES\EsVideo;
...
public function estest1()
{
    $result = EsVideo::searchByVideo('二滑','content');
    return $this->writeJson(200,'ok',$result);
}

结果

优化

创建App\Model\ES\EsBase.php

namespace App\Model\ES;

use EasySwoole\Component\Di;

class EsBase
{
    public $client = null;

    public function __construct()
    {
        $this->client = Di::getInstance()->get('ES');
    }

    /*
     * 搜索视频名/内容
     * $index : 索引名
     * $type : 类型名
     * $default_video_fields[] : 字段名
     * */
    public function searchByVideo($search, $fields = [])
    {
        $search = trim($search);
        if (empty($search)) {
            return [];
        }
        if (empty($fields)) {
            $fields = $this->default_video_fields;
        }
        $params = [
            "index" => $this->index,
            "type" => $this->type,
            'body' => [
                'query' => [
                    'multi_match' => [
                        'query' => $search,
                        'fields' => $fields
                    ]
                ]
            ]
        ];
        $result = $this->client->search($params);
        return $result;
    }
}

修改App\Model\ES\EsVideo.php

namespace App\Model\ES;

class EsVideo extends EsBase
{
    // 指定索引
    public $index = 'small_video';
    // 指定类型
    public $type = '_doc';
    // 默认查询字段
    public $default_video_fields = ['name', 'content'];
}

请求实例

use App\Model\ES\EsVideo;
...
public function estest1()
{
    $EsClient = new EsVideo();
    $result = $EsClient->searchByVideo('二');
    return $this->writeJson(200, 'ok', $result);
}

这样我们可以将以后的搜索都抽离出来作为公共的.只需要修改模型的成员属性就可以了.非常的方便~

16.gif

Last modification:February 18th, 2020 at 10:26 pm