Elasticsearch全文搜索引擎-PHP使用教程

用Composer来生成php版的elasticsearch框架

 

如果你还没有安装Composer的话请看:Composer安装教程文章

 

1、声明依赖关系:

        比方说,你的项目中需要一个php版的elasticsearch框架。为了将它添加到你的项目中(下载),你所需要做的就是创建一个 composer.json 文件,其中描述了项目的依赖关系。注意文件要放在你执行composer命令的目录中

{

    "require":{

        "elasticsearch/elasticsearch":"~2.0"

    }

}

2、cmd切换到要下载elasticsearch框架的目录,然后执行命令:composer install

     如有出错误信息:

      [Composer\Downloader\TransportException]

      Content-Length mismatch, received 583439 bytes out of the expected 1215108

     解决办法:切换国内镜像地址,再执行操作

      1、通过命令切换如下:(最终修改的是composer.json)

      composer config -g repo.packagist composer https://packagist.phpcomposer.com

      2、直接修改 composer.json (其实跟方法1是一样的。)

{

    "require":{

        "elasticsearch/elasticsearch":"~2.0"

    },

    "repositories": {

        "packagist": {

            "type": "composer",

            "url": "https://packagist.phpcomposer.com"

        }

    }

}

001.png

PHP使用elasticsearch教程

 

下面我们讲一下基本使用方法,需要获取更多使用教程和方法请看官方文档:https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_overview.html

想直接通过文件查看其他方法可以打开以下文件查看(基本使用的方法都在里面):

1、\elasticsearch\src\Elasticsearch\Client.php中的方法

2、\elasticsearch\Namespaces\IndicesNamespace.php中的方法

ThinkPHP中的模型:

<?php

/**

 * Elasticsearch检索引擎模型

 */

namespace app\index\model;

use Elasticsearch\ClientBuilder;  

   

class Elasticsearch

{

    //配置

    private $config = [

        'hosts' => ['http://127.0.0.1:9200']

    ];

    private $api;

    public function __construct()

    {

        #include(APP_PATH .'/vendor/autoload.php');

        #require_once EXTEND_PATH . 'org/elasticsearch/autoload.php';

        import('org.elasticsearch.autoload', EXTEND_PATH);

        $this->api = ClientBuilder::create()->setHosts($this->config['hosts'])->build(); 

    }

 

    /*************************************************************

    /**

     * 索引一个文档

     * 说明:索引没有被创建时会自动创建索引

     */

    public function addOne()

    {

        $params = [];  

        $params['index'] = 'xiaochuan';  

        $params['type']  = 'cat';  

        $params['id']  = '20180407001';  # 不指定就是es自动分配

        $params['body']  = array('name' => '小川编程');  

        return $this->api->index($params);

    }

 

    /**

     * 索引多个文档

     * 说明:索引没有被创建时会自动创建索引

     */

    public function addAll()

    {

        $params = [];

        for($i = 1; $i < 21; $i++) {  

            $params['body'][] = [

                'index' => [

                    '_index' => 'test_index'.$i,

                    '_type'  => 'cat_test',

                    '_id'    => $i,

                ]

            ];  

            $params['body'][] = [  

                'name' => '小川编程'.$i,  

                'content' => '内容'.$i  

            ];

        }  

        return $this->api->bulk($params);  

    }

 

    /**

     * 获取一个文档

     */

    public function getOne()

    {

        $params = [];  

        $params['index'] = 'xiaochuan';  

        $params['type']  = 'cat';  

        $params['id']    = '20180407001';  

        return $this->api->get($params); 

    }

 

    /**

     * 搜索文档

     */

    public function search()

    {

        $params = [];

        $params['index'] = 'xiaochuan';  

        $params['type']  = 'cat';  

        $params['body']['query']['match']['name'] = '小川编程';  

        return $this->api->search($params); 

    }

 

    /**

     * 删除文档

     * 说明:文档删除后,不会删除对应索引。

     */

    public function delete()

    {

        $params = [];  

        $params['index'] = 'xiaochuan';  

        $params['type'] = 'cat';  

        $params['id'] = '20180407001';  

        return $this->api->delete($params);  

    }

 

    /*************************************************************

    /**

     * 创建索引

     */

    public function createIndex()

    {

        $params = [];

        $params['index']  = 'xiaochuan'; 

        return $this->api->indices()->create($params);  

    }

       

      /**

     * 删除索引:匹配单个 | 匹配多个

     * 说明: 索引删除后,索引下的所有文档也会被删除

     */

      public function deleteIndex()

      {  

          $params = [];

          $params['index'] = 'test_index';  # 删除test_index单个索引

          #$params['index'] = 'test_index*'; # 删除以test_index开始的所有索引

        return $this->api->indices()->delete($params);  

      }

 

      /*************************************************************

      /**

     * 设置索引配置

     */

      public function setIndexConfig()

      {  

          $params = [];

          $params['index'] = 'xiaochuan';  

        $params['body']['index']['number_of_replicas'] = 0;  

        $params['body']['index']['refresh_interval'] = -1;  

        return $this->api->indices()->putSettings($params);  

      }

 

      /**

     * 获取索引配置

     */

      public function getIndexConfig()

      {

          # 单个获取条件写法

        $params['index'] = 'xiaochuan';  

        # 多个获取条件写法

        //$params['index'] = ['xiaochuan', 'test_index'];  

        return $this->api->indices()->getSettings($params);  

      }

 

    /**

     * 设置索引映射

     */

      public function setIndexMapping()

      {

          #  设置索引和类型 

        $params['index'] = 'xiaochuan';  

        $params['type']  = 'cat';  

           

        #  向现有索引添加新类型

        $myTypeMapping = array(  

            '_source' => array(  

                'enabled' => true  

            ),  

            'properties' => array(  

                'first_name' => array(  

                    'type' => 'string',  

                    'analyzer' => 'standard'  

                ),  

                'age' => array(  

                    'type' => 'integer'  

                )  

            )  

        );  

        $params['body']['cat'] = $myTypeMapping;  

           

        #  更新索引映射 

        $this->api->indices()->putMapping($params);  

      }

 

      /**

     * 获取索引映射

     */

      public function getIndexMapping()

      {  

          #  获取所有索引和类型的映射  

        $ret = $this->api->indices()->getMapping();  

         

        /*  

        #  获取索引为:xiaochuan的映射

        $params['index'] = 'xiaochuan';  

        $ret = $this->api->indices()->getMapping($params);  

           

        #  获取类型为:cat的映射

        $params['type'] = 'cat';  

        $ret = $this->api->indices()->getMapping($params);  

           

        #  获取(索引为:xiaochuan和 类型为:cat)的映射

        $params['index'] = 'xiaochuan';  

        $params['type']  = 'cat'  

        $ret = $this->api->indices()->getMapping($params);  

           

        #  获取索引为:xiaochuan和test_index的映射

        $params['index'] = ['xiaochuan', 'test_index'];  

        $ret = $this->api->indices()->getMapping($params); 

        */

 

        return $ret;

      }

 

}

其他形式用法测试:

test.php

<?php   

require_once('vendor/autoload.php');  

use Elasticsearch\ClientBuilder;  

   

   

function get_conn(){  

    $host = 'localhost';  

    $dbname = 'mraz';  

    $user = 'root';  

    $passwd = '111111';  

   

   

    $conn = new PDO("mysql:dbname=$dbname;host=$host",$user,$passwd);  

    return $conn;  

}  

   

   

function create_index(){  

    //Elastic search php client  

   

   

   

   

    $client = Elasticsearch\ClientBuilder::create()->build();  

    $sql    = "SELECT * FROM emp";  

    $conn   = get_conn();  

    $stmt   = $conn->query($sql);  

    $rtn    = $stmt->fetchAll();  

   

   

    //delete index which already created  

    $params = array();  

    $params['index'] = 'emp_index';  

    $client->indices()->delete($params);  

       

    //create index on log_date,src_ip,dest_ip  

    $rtnCount = count($rtn);  

    for($i=0;$i<$rtnCount;$i++){  

        $params = array();  

        $params['body'] = array(  

            'id'       => $rtn[$i]['id'],  

            'fdName'   => $rtn[$i]['fdName'],  

            'fdAge'    => $rtn[$i]['fdAge'],  

            'fdStatus' => $rtn[$i]['fdStatus']  

        );  

        $params['index'] = 'emp_index';  

        $params['type']  = 'emp_type';  

           

        //Document will be indexed to log_index/log_type/autogenerate_id          

        $client->index($params);  

    }  

    echo 'create index done!';  

}  

   

   

function search(){  

    //Elastic search php client  

    $client = Elasticsearch\ClientBuilder::create()->build();  

    $params = array();  

    $params['index'] = 'emp_index';  

    $params['type'] = 'emp_type';  

    $params['body']['query']['match']['fdStatus'] = '1';  

    $params['body']['sort'] = array('fdAge'=>array('order'=>'desc'));  

    $params['size'] = 3;    

    $params['from'] = 1;    

    $rtn = $client->search($params);  

    var_dump($rtn);  

}  

   

   

set_time_limit(0);  

// create_index();  

search();  

?>

1)创建:

include('./vendor/autoload.php');  

$elastic = new Elasticsearch\Client();  

$index['index'] = 'log';  //索引名称  

$index['type'] = 'ems_run_log'; //类型名称  

$data['body']['settings']['number_of_shards'] = 5;  //主分片数量  

$data['body']['settings']['number_of_replicas'] = 0; //从分片数量  

$elastic->indices()->create($index);

2)插入索引数据:

include('./vendor/autoload.php');  

$elastic = new Elasticsearch\Client();  

$index['index'] = 'log'; //索引名称  

$index['type'] = 'ems_run_log'; //类型名称  

$index['id'] = 1   //不指定id,系统会自动生成唯一id  

$index['body'] = array(  

  'mac' => 'fcd5d900beca',  

  'customer_id' => 3,  

  'product_id' => 5,  

  'version' => 2  

);  

$elastic->index($index);

3)查询:

include('./vendor/autoload.php');  

$elastic = new Elasticsearch\Client();  

$index['index'] = 'log'; //索引名称  

$index['type'] = 'ems_run_log'; //类型名称  

$index['body']['query']['match']['mac'] = 'fcd5d900beca';  

$index['size'] = 10;  

$index['from'] = 200;  

$elastic->search($index);  

 

#相当于sql语句:select*from ems_run_log where mac='fcd5d900beca' limit 200,10;
include('./vendor/autoload.php');  

$elastic = new Elasticsearch\Client();  

$index['index'] = 'log'; //索引名称  

$index['type'] = 'ems_run_log'; //类型名称  

$index['body']['query']['bool']['must'] = array(  

    array('match' => array('mac' => 'fcd5d900beca')),  

    array('match' => array('product_id' => 20))  

   );  

$index['size'] = 10;  

$index['from'] = 200;  

$elastic->search($index);  

 

#相当于sql语句:select*from ems_run_log where mac='fcd5d900beca' and product_id=20 limit 200,10;
include('./vendor/autoload.php');  

$elastic = new Elasticsearch\Client();  

$index['index'] = 'log'; //索引名称  

$index['type'] = 'ems_run_log'; //类型名称  

$index['body']['query']['bool']['should'] = array(  

      array('match' => array('mac' => 'fcd5d900beca')),  

      array('match' => array('product_id' => 20))  

     );  

$index['size'] = 10;  

$index['from'] = 200;  

$elastic->search($index);  

 

#当于sql语句:select*from ems_run_log where mac='fcd5d900beca' or product_id=20 limit 200,10;
include('./vendor/autoload.php');  

$elastic = new Elasticsearch\Client();  

$index['index'] = 'log'; //索引名称  

$index['type'] = 'ems_run_log'; //类型名称  

$index['body']['query']['bool']['must_not'] = array(  

   array('match' => array('mac' => 'fcd5d900beca')),  

   array('match' => array('product_id' => 20))  

  );  

$index['size'] = 10;  

$index['from'] = 200;  

$elastic->search($index);  

 

#相当于sql语句:select*from ems_run_log where mac!='fcd5d900beca' and product_id!=20 limit 200,10;
include('./vendor/autoload.php');  

$elastic = new Elasticsearch\Client();  

$index['index'] = 'log'; //索引名称  

$index['type'] = 'ems_run_log'; //类型名称  

$index['body']['query']['range'] = array(  

   'id' => array('gte' => 20,'lt' => 30);  

 );  

$index['size'] = 10;  

$index['from'] = 200;  

$elastic->search($index);  

 

#相当于sql语句:select*from ems_run_log where id>=20 and id<30  limit 200,10;

4)删除文档:

include('./vendor/autoload.php');  

$elastic = new Elasticsearch\Client();  

$index['index'] = 'test';  //索引名称  

$index['type'] = 'ems_test'; //类型名称  

$index['id'] = 2;   

$elastic->delete($index);
include('./vendor/autoload.php');  

$elastic = new Elasticsearch\Client();  

$index['index'] = 'log'; //索引名称  

$index['type'] = 'ems_run_log'; //类型名称  

$index['body']['query']['bool']['must_not'] = array(  

   array('match' => array('mac' => 'fcd5d900beca')),  

   array('match' => array('product_id' => 20))  

  );  

$index['size'] = 10;  

$index['from'] = 200;  

$elastic->search($index);  

 

#相当于sql语句:select*from ems_run_log where mac!='fcd5d900beca' and product_id!=20 limit 200,10;
include('./vendor/autoload.php');  

$elastic = new Elasticsearch\Client();  

$index['index'] = 'log'; //索引名称  

$index['type'] = 'ems_run_log'; //类型名称  

$index['body']['query']['range'] = array(  

   'id' => array('gte' => 20,'lt' => 30);  

 );  

$index['size'] = 10;  

$index['from'] = 200;  

$elastic->search($index);  

 

#相当于sql语句:select*from ems_run_log where id>=20 and id<30  limit 200,10;

5)PHP 版elasticsearch 数据更新update和updateByQuery方法

根据id去更新,这时候调用的是update方法:

     public static function updateEsById($id,$data = [])
        {
    
            if (empty($id) || empty($data)){
                return false;
            }
            $es = new Elastic();
            $data=[
                'index' => self::$es_index,
                'type' => self::$es_type,
                'id' => $id,
                'body' => [
                    'doc'=> $data //这里的data是个一维关联数组,和常用的ORM更新方法参数一致。
                ]
            ];
    
           $res = $es->update($data);
           return $res['result'];
        }

不知道需要更新数据的id,或者说我们需要根据条件批量更新,这时候可以用updateByQuery方法:

条件是多个,并且都是=,当然也可以根据range等逻辑运算进行过滤

    /**
         * Notes :
         * @param array $where
         * @param string $field
         * @param string $value
         * @return bool
         * author: leojen
         * @date: 18-11-21 下午6:06
         */
        public static function upByWhere($where = [],$data = [])
        {
    
            if (empty($where) || empty($data)){
                return false;
            }
    
            $fields = '';
            foreach ($data as $k=>$v){
                $fields .="ctx._source.{$k} = $v;";
            }
            $fields = trim($fields,';');
            $params = [
                'index' => self::$es_index,
                'type' => self::$es_type,
                'body' => [
                    'query' => [
                        'bool'=>['must'=>[]]
                    ],
                    'script'=>[
                        "inline"=> $fields,
                        'lang'=>'painless'
    
                    ]
                ]
            ];
    
            foreach ($where as $key=>$val){
                $params['body']['query']['bool']['must'][] =  [
                    'term' => [
                        $key =>$val
                    ]
                ];
            }
            $client = new Elastic();
            return  $client->updateByQuery($params);
    
        }

原文地址:https://www.cnblogs.com/ljl123/p/9505773.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值