上路抗压,野爹常来

php使用elasticsearch

ES 功能类库

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/4/2
 * Time: 17:36
 */

use Elasticsearch\ClientBuilder;

class ES{
    private $es;
    private $host;

    /**
     * 构造函数
     * ES constructor.
     */
    public function __construct()
    {
        require(Spider_PATH . "config/config.elasticsearch.php");
        $this->host = $es_config;//es服务器地址
        $this->es = $this->client();//连接es
    }

    /**
     * 连接es
     * @return \Elasticsearch\Client|mixed
     */
    public function client(){
        $this->es = ClientBuilder::create()->setHosts($this->host)->build();
        return $this->es;
    }

    /**
     * 创建索引  可根据数据库自动创建索引
     * @param $index    string  数据表名称
     * @param $type     string  type
     * @param $properties array   数据结构
     * @return array
     */
    public function esCreateIndex($index,$type,$properties = []){
        $params = [
            'index' => $index,
            'body' => [
                'settings' => [
                    'number_of_shards' => 1,
                    'number_of_replicas' => 0
                ],
                'mappings' => [//映射
                    '_default_' => [//默认配置,每个类型缺省的配置使用默认配置
                        '_all' => [
                            'enabled' => 'false'//关闭所有字段的检索
                        ],
                        '_source'=>[   //  存储原始文档
                            'enabled' => 'true'
                        ],
                        'properties' => $properties,
                    ],
                    $type => [
                        'properties' => [],
                    ],
                ],
            ],
        ];
        return $this->es->indices()->create($params);
    }

    /**
     * 判断索引是否存在
     * @param $index    string  索引
     * @return bool
     */
    public function exists($index){
        $params = [
            'index' => $index
        ];
        return $this->es->indices()->exists($params);
    }

    /**
     * 查看mappings
     * @param $index    string  索引
     * @return array
     */
    public function getMappings($index){
        $params = [
            'index' => $index
        ];
        return $this->es->indices()->getMapping($params);
    }

    /**
     * 设置mappings
     * @param $index    string  索引
     * @param $type     string  type
     * @param $properties array 
     * @return array
     */
    public function putMappings($index,$type,$properties){
        $params = [
            'index' => $index,
            'type' => $type,
            'body' => [
                'properties' => $properties,
            ],
        ];
        return $this->es->indices()->putMapping($params);
    }

    /**
     * es分页搜索
     * @param $index    string   索引
     * @param $type     string   type
     * @param $form     int      页数
     * @param $size     int      每页显示多少条
     * @param $query    array    搜索条件
     * @return array
     */
    public function esSearch($index,$type,$query,$form = 0,$size = 10){
        $params = [
            'index' => $index,
            'type' => $type,
            'body' => array_merge([
                'from' => $form * $size,
                'size' => $size,
            ],$query),
        ];
        return $this->es->search($params);
    }

    /**
     * 统计
     * @param $index    string  索引
     * @param $type     string  type
     * @param $body     array   查询条件
     * @return array
     */
    public function esCount($index,$type,$body = []){
        $params = [
            'index' => $index,
            'type' => $type,
            'body' => $body,
        ];
        return $this->es->count($params);
    }

    /**
     * es通过id获取|删除|修改
     * @param $index    string  索引
     * @param $type     string  type
     * @param $id       string  id
     * @param $opera    string  get获取 del删除 edit修改
     * @param $body     array   更新数据
     * @return array
     */
    public function esOperaById($index,$type,$id,$opera = 'get',$body = []){
        $params = [
            'index' => $index,
            'type' => $type,
            'id' => $id,
        ];
        if ($opera == 'del'){
            return $this->es->delete($params);
        }elseif ($opera == 'edit'){
            $params['body'] = $body;
            return $this->es->update($params);
        }
        return $this->es->get($params);
    }

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

    /**
     * es插入单条
     * @param $index    string  索引
     * @param $type     string  type
     * @param $body     array   插入数据
     * @return array
     */
    public function esIndexOne($index,$type,$body){
        $params = [
            'index' => $index,
            'type' => $type,
            'body' => $body
        ];
        return $this->es->index($params);
    }

    /**
     * 插入多条
     * @param $index    string  索引
     * @param $type     string  type
     * @param $body     array  数据
     * @return array
     */
    public function esBulk($index,$type,$body){
        $params = [
            'index' => $index,
            'type' => $type,
            'body' => $body
        ];
        return $this->es->bulk($params);
    }
}

使用

require_once("../vendor/autoload.php");
require_once("./es/class.es.php");

$es = new ES();
//通过查询 数据表 字段 创建索引
$index = $es->esCreateIndex("sm_chenggu","chenggu",[],$db);
//$db为数据库连接类库,如下图

//判断索引是否存在
$bool = $es->exists('sm_chenggu');//索引名称
//查看mappings配置
$mappings = $es->getMappings('sm_chenggu');//索引名称
//设置字段类型
$properties = [
    'id' => [
        'type' => 'text',//原先字段类型必须一致
        'fields' => [//设置的其余类型
            'raw' => [
                'type' => 'keyword'
            ],
        ],
    ]
],
$fielddata = $es->putMappings('sm_chenggu','chenggu',$properties);
//es搜索
//具体query请自行搜索相关文档,网上很多
//https://www.cnblogs.com/bigben0123/articles/11075949.html
$query = [
    'query' => [
        'bool' => [
            'must' => [
                [
                    'match_phrase' => ['title' => $q]//搜索条件 多个条件
                ],
            ],
        ],
    ],
    'sort' => [
        'id' => 'desc',
    ],//排序
    '_source' => [
        'id','title'
    ],//显示字段
];
$data = $es->esSearch('sm_chenggu','chenggu',$query);
//统计
//$body与es搜索中的$query一样,都是搜索条件,相当于mysql的where
$body = [
    'query' => [
        'bool' => [
            'must' => [
                [
                    'match_phrase' => ['title' => $q]
                ],
            ],
        ],
    ],
];
$count = $es->esCount('suanming', 'zgjm_data', $body);
//es通过id获取|删除|修改
$data = $es->esOperaById('sm_chenggu','chenggu','1','get');//获取
$del = $es->esOperaById('sm_chenggu','chenggu','1','del');//删除
$edit = $es->esOperaById('sm_chenggu','chenggu','1','edit',$body);//修改
//删除index索引
$del_index = $es->esDel('sm_chenggu');
//es插入单条
$res = $es->esIndexOne('sm_chenggu','chenggu',$body);
//插入多条
for ($i = 0;$i <= $page;$i++){
    $j = $i * 1000;
    $k = ($i + 1) * 1000;
    if ($i == $page){
        $k = $j + $num;
    }
    //分页搜索,每次1000条
    $sql = "select * from $db_name limit $j,$k";
    $data = $db->get_all($sql);
    foreach ($data as $key=>$val){
        foreach ($column as $k=>$v){
            $val[$v] = $this->operaStr($val[$v]);
        }
        //数据拼装
        $body[] = [
            'index' => [
                '_id' => $val['id'],
            ],
        ];
        $body[] = $val;
    }
    $es->esBulk($index,$db_name,$body);
}
posted @ 2021-04-23 10:09  上路抗压  阅读(324)  评论(0编辑  收藏  举报