PHP中使用ElasticSearch

2,305 阅读1分钟

ElasticSearch是一个基于Lucene的稳定的、分布式、RESTFul的搜索引擎。其实所谓的RestFul就是它提供URL供你调用(建立索引和进行检索),不过直接这样使用实在是太凶残了。所以,它也提供了一系列client包,相当于将curl请求封装了,client包支持的语言包括Java、PHP、Python、Ruby和Perl等等。

PHP版的client包叫做elasticsearch-php,可以在Github上下载。地址如下:https://github.com/elasticsearch/elasticsearch

要使用elasticsearch-php有如下三个要求:

  1. PHP的版本在5.3.9以上,我用的是PHP5.3.23

  2. 在项目中使用Composor来管理包,下载地址如下:https://getcomposer.org/

  3. 在php.ini中开启curl和openssl

启动elasticsearch很简单,直接进入解压目录,运行elasticsearch.bat就可以了,看到最后console输出start,就启动成功了。

接下来介绍如何使用elasticsearch-php:

  1. 新建一个文件夹取名为test,此为项目文件夹

  2. 在里面放入一个命名为composer.json的文件,文件内容为:

{
        "require":{
        "elasticsearch/elasticsearch" : "~1.2"
    }
}
  1. composer install

  2. 这个时候test文件夹下面应该会出现vendor文件夹,里面有elasticsearch、composer、guzzle等文件夹,很多内容

  3. 实现代码

<?php
require_once('vendor/autoload.php');
function get_conn(){
    $host = 'ip';
    $dbname = 'dbname';
    $user = 'user';
    $passwd = 'passwd';

    $conn = new PDO("pgsql:dbname=$dbname;host=$host",$user,$passwd);
    return $conn;
}

function create_index(){
    //Elastic search php client
    $client = new Elasticsearch\Client();
    $sql = "SELECT * FROM log";
    $conn = get_conn();
    $stmt = $conn->query($sql);
    $rtn = $stmt->fetchAll();

    //delete index which already created
    $params = array();
    $params['index'] = 'log_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(
            'log_date' => $rtn[$i]['log_date'],
            'src_ip' => $rtn[$i]['src_ip'],
            'dest_ip' => $rtn[$i]['dest_ip']
        );
        $params['index'] = 'log_index';
        $params['type'] = 'log_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 = new Elasticsearch\Client();
    $params = array();
    $params['index'] = 'log_index';
    $params['type'] = 'log_type';
    $params['body']['query']['match']['src_ip'] = '1.122.33.141';

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

set_time_limit(0);
//create_index();
search();
?>