PHP中使用ElasticSearch

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();
?>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,380评论 19 139
  • Awesome PHP 一个PHP资源列表,内容包括:库、框架、模板、安全、代码分析、日志、第三方库、配置工具、W...
    guanguans阅读 11,137评论 0 47
  • Composer Repositories Composer源 Firegento - Magento模块Comp...
    零一间阅读 9,341评论 1 66
  • 通常网络请求返回的是JSON数据,使用ObjectMapper可以让JSON数据直接转化为对象,而使用Alamof...
    Harely阅读 4,850评论 0 0
  • 天天用英语365天第125天 张雷 Birthday blues is something that many f...
    小春hdek阅读 3,342评论 0 0