PHP ElasticSearch的使用

时间:2023-03-09 22:28:39
PHP ElasticSearch的使用

系统是Windows server 2003。

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

PHP版的client包叫做elasticsearch-php,可以在Git_hub上下载。地址如下: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,需要JDK的版本大于6,最好选择8吧,因为7有漏洞....

截一张需要的包图:

PHP ElasticSearch的使用

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

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

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

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

  1. {
  2. "require":{
  3. "elasticsearch/elasticsearch" : "~1.2"
  4. }
  5. }

3.将composer.phar拷贝到test文件夹中,cd 到test文件夹,输入命令:php composer.phar install --no-dev  等待安装成功

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

4.这个时候,就可以使用elasticsearch进行建立索引和进行检索了

  1. <?php
  2. require_once('vendor/autoload.php');
  3. function get_conn(){
  4. $host = 'ip';
  5. $dbname = 'dbname';
  6. $user = 'user';
  7. $passwd = 'passwd';
  8. $conn = new PDO("pgsql:dbname=$dbname;host=$host",$user,$passwd);
  9. return $conn;
  10. }
  11. function create_index(){
  12. //Elastic search php client
  13. $client = new Elasticsearch\Client();
  14. $sql = "SELECT * FROM log";
  15. $conn = get_conn();
  16. $stmt = $conn->query($sql);
  17. $rtn = $stmt->fetchAll();
  18. //delete index which already created
  19. $params = array();
  20. $params['index'] = 'log_index';
  21. $client->indices()->delete($params);
  22. //create index on log_date,src_ip,dest_ip
  23. $rtnCount = count($rtn);
  24. for($i=0;$i<$rtnCount;$i++){
  25. $params = array();
  26. $params['body'] = array(
  27. 'log_date' => $rtn[$i]['log_date'],
  28. 'src_ip' => $rtn[$i]['src_ip'],
  29. 'dest_ip' => $rtn[$i]['dest_ip']
  30. );
  31. $params['index'] = 'log_index';
  32. $params['type'] = 'log_type';
  33. //Document will be indexed to log_index/log_type/autogenerate_id
  34. $client->index($params);
  35. }
  36. echo 'create index done!';
  37. }
  38. function search(){
  39. //Elastic search php client
  40. $client = new Elasticsearch\Client();
  41. $params = array();
  42. $params['index'] = 'log_index';
  43. $params['type'] = 'log_type';
  44. $params['body']['query']['match']['src_ip'] = '1.122.33.141';
  45. $rtn = $client->search($params);
  46. var_dump($rtn);
  47. }
  48. set_time_limit(0);
  49. //create_index();
  50. search();
  51. ?>

建立索引成功,可以看到“create index done!”

查询成功,可以看到返回的结果数组。