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有漏洞....

截一张需要的包图:


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


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


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

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

{
	"require":{
		"elasticsearch/elasticsearch" : "~1.2"
	}
}
3.将composer.phar拷贝到test文件夹中,cd 到test文件夹,输入命令:php composer.phar install --no-dev  等待安装成功

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

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

<?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();
?>

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

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


  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值