Skip to content

Instantly share code, notes, and snippets.

@gitfrage
Last active November 29, 2016 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gitfrage/36c5508861567a811d54ab242abc0868 to your computer and use it in GitHub Desktop.
Save gitfrage/36c5508861567a811d54ab242abc0868 to your computer and use it in GitHub Desktop.
<?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