Elasticseach PHP API
首先要安装php-elasticsearch扩展,要求PHP版本>=5.3
php composer.phar require elasticsearch/elasticsearch
在PHP中的应用:
require 'vendor/autoload.php'; $client = new Elasticsearch\Client();
如果要指定配置
$params = array();$params['hosts'] = array ( '192.168.1.1:9200', // IP + Port //'192.168.1.2', // Just IP //'mydomain.server.com:9201', // Domain + Port //'mydomain2.server.com', // Just Domain //'https://localhost', // SSL to localhost //'https://192.168.1.3:9200', // SSL to IP + Port //'http://user:pass@localhost:9200', // HTTP Basic Auth //'https://user:pass@localhost:9200', // SSL + HTTP Basic Auth ); $client = new Elasticsearch\Client($params);
创建索引
$indexParams['index'] = 'my_index'; //Index Settings $indexParams['body']['settings']['number_of_shards'] = 3; $indexParams['body']['settings']['number_of_replicas'] = 2; $client->indices()->create($indexParams);
删除索引
$deleteParams['index'] = 'my_index'; $client->indices()->delete($deleteParams);
增加一个文档记录
$params = array(); $params['body'] = array('testField' => 'abc'); $params['index'] = 'my_index'; $params['type'] = 'my_type'; $params['id'] = 'my_id';// 这里不指定Id就是使用自增Id $ret = $client->index($params);
修改一个文档记录
$params = array(); $params['body'] = array('testField' => 'efg'); $params['index'] = 'my_index'; $params['type'] = 'my_type'; $params['id'] = 'my_id'; $ret = $client->update($params);
批量增加
for($i = 0; $i < 100; $i++) { $params['body'][] = array( 'index' => array( '_id' => $i ) ); $params['body'][] = array( 'my_field' => 'my_value', 'second_field' => 'some more values' ); } $responses = $client->bulk($params);
检查文档是否存在
$params['index'] = 'my_index'; $params['type'] = 'my_type'; $params['id'] = 'my_id'; $ret = $client->exists($params);
匹配查询
$params['index'] = 'my_index'; $params['type'] = 'my_type'; $params['body']['query']['match']['testField'] = 'abc'; $results = $client->search($params);
布尔查询
$params['index'] = 'my_index'; $params['type'] = 'my_type'; $params['body']['query']['bool']['must'] = array( array('match' => array('testField' => 'abc')), array('match' => array('anotherTestField' => 'xyz')), ); $results = $client->search($params);
组合查询
$params['index'] = 'my_index'; $params['type'] = 'my_type'; $filter = array(); $filter['term']['my_field'] = 'abc'; $query = array(); $query['match']['my_other_field'] = 'xyz'; $params['body']['query']['filtered'] = array( "filter" => $filter, "query" => $query ); $results = $client->search($params);
基本上平时会使用的就是这些了,还有想了解更多的同学可以自行去查看开发文档。
原创文章如转载,请注明出处,本文首发于彭超的博客
文章版权声明:除非注明,否则均为彭超的博客原创文章,转载或复制请以超链接形式并注明出处。
继续浏览有关 elasticsearchphp 的文章
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。