1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
<?php
/**
* Copyright 2011-2017 Horde LLC (http://www.horde.org/)
*
* See the enclosed file LICENSE for license information (BSD). If you
* did not receive this file, see http://www.horde.org/licenses/bsd.
*
* @author Chuck Hagenbuch <chuck@horde.org>
* @category Horde
* @license http://www.horde.org/licenses/bsd BSD
* @package ElasticSearch
*/
/**
* ElasticSearch client class
*
* @author Chuck Hagenbuch <chuck@horde.org>
* @category Horde
* @copyright 2011-2017 Horde LLC
* @license http://www.horde.org/licenses/bsd BSD
* @package ElasticSearch
*/
class Horde_ElasticSearch_Client
{
protected $_server = 'http://localhost:9200/';
protected $_httpClient;
public function __construct($server, Horde_Http_Client $httpClient)
{
$this->_server = $server;
$this->_httpClient = $httpClient;
}
/**
* curl -X GET {SERVER}/_status
*/
public function status($index = null)
{
return $this->_request($this->_path($index, '_status'));
}
/**
* curl -X GET {SERVER}/{INDEX}/{TYPE}/_search?q= ...
*/
public function search($index, $type, $q)
{
return $this->_request($this->_path($index, $type, '_search') . '?' . http_build_query(array('q' => $q)));
}
/**
* curl -X GET {SERVER}/{INDEX}/{TYPE/{ID}
*/
public function get($index, $type, $id)
{
return $this->_request($this->_path($index, $type, $id));
}
/**
* curl -X PUT {SERVER}/{INDEX}/{TYPE}/{ID} -d ...
*/
public function add($index, $type, $id, $data)
{
return $this->_request($this->_path($index, $type, $id), 'PUT', $data);
}
/**
* curl -X GET {SERVER}/{INDEX}/{TYPE}/_count -d {matchAll:{}}
*/
public function count($index, $type)
{
return $this->_request($this->_path($index, $type, '_count'), 'GET', '{ matchAll:{} }');
}
/**
* curl -X PUT {SERVER}/{INDEX}/{TYPE}/_mapping -d ...
*/
public function map($index, $type, $data)
{
return $this->_request($this->_path($index, $type, '_mapping'), 'PUT', $data);
}
protected function _request($path, $method = 'GET', $data = null, $headers = array())
{
try {
$result = $this->_httpClient->request($method, $this->_server . $path, $data, $headers);
return json_decode($result->getBody());
} catch (Horde_Http_Exception $e) {
throw new Horde_ElasticSearch_Exception($e->getMessage(), $e->getCode(), $e);
}
}
protected function _path()
{
$path = array_filter(func_get_args());
foreach ($path as &$element) { $element = urlencode($element); }
return implode('/', $path);
}
}
|