Last active
November 29, 2016 08:04
-
-
Save gitfrage/36c5508861567a811d54ab242abc0868 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# @author gitfrage | |
# @license MIT | |
# mico php client for elasticsearch | |
# minimal API similar to the official client https://github.com/elastic/elasticsearch-php | |
function init($host, $port, $user = '', $pass = '') | |
{ | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_FORBID_REUSE, false); | |
$url = "http://{$host}:{$port}"; | |
if (!empty($user) && !empty($pass)) { | |
curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$pass); | |
} | |
return function ($method, $location, array $body = []) use ($url, $ch) { | |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); | |
curl_setopt($ch, CURLOPT_URL, "{$url}/{$location}"); | |
if (!empty($body)) { | |
if ($location == '/_bulk') { | |
$strbody = ''; | |
foreach ($body as $item) { | |
$strbody .= json_encode($item) . "\n"; | |
} | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $strbody); | |
} else { | |
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body)); | |
} | |
} | |
$res = curl_exec($ch); | |
if ($res !== false) { | |
return json_decode($res, true); | |
} | |
trigger_error('init: '.curl_error($ch), E_USER_ERROR); | |
}; | |
} | |
function insert($connect, $params) | |
{ | |
return $connect('PUT', "{$params['index']}/{$params['type']}/{$params['id']}", $params['body']); | |
} | |
function get($connect, $params) | |
{ | |
return $connect('GET', "{$params['index']}/{$params['type']}/{$params['id']}"); | |
} | |
function search($connect, $params) | |
{ | |
if (!isset($params['size'])) { | |
$params['size'] = 10; | |
} | |
return $connect('POST', "{$params['index']}/{$params['type']}/_search?size={$params['size']}", $params['body']); | |
} | |
function update($connect, $params) | |
{ | |
return $connect('POST', "{$params['index']}/{$params['type']}/{$params['id']}/_update", $params['body']); | |
} | |
function bulk($connect, $params) | |
{ | |
return $connect('POST', "/_bulk", $params['body']); | |
} | |
function delete($connect, $params) | |
{ | |
return $connect('DELETE', "{$params['index']}/{$params['type']}/{$params['id']}"); | |
} | |
############################## usage | |
$esh = init('localhost', 9200, 'user', 'pass'); | |
$params = [ | |
'index' => 'packetbeat-2016.11.21', | |
'type' => 'mysql', | |
'body' => ['query' => [[ 'match' => [ 'method' => 'INSERT' ]]] | |
]; | |
$packetbeat = search($esh, $params); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment