ElasticSearch Rest API Example Using PHP

This tutorial help to access elastic search data using Rest API.I will create simple PHP rest call to access Elstaicsearch data using restful api with some search parameters.

Elasticsearch is a distributed, Restful search and analytics engine capable of solving a growing number of use cases.it centrally stores your data so you can discover the expected and uncover the unexpected. Elasticsearch as a Service offering available on Amazon Web Services (AWS) and Google Cloud Platform (GCP) powered by the creators of Elasticsearch, Logstash, Kibana, and Beats.

Elasticsearch provides two ways to run searches into datas,One is by sending search parameters through the REST request URI and the other by sending them through the[REST request body]. The request body method allows you to define your searches in a more readable JSON format.We will create example using request body method.

How to Search Data Using Elasticsearch API

I am using guzzle rest client to access Elasticsearch API.We will create guzzle instance using rest api host name and authorization token.We will set Content-Type is application/json and add Authorization into rest client header.

require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
$token = 'XXXXXXXXXX';

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'restapi url', //https://hostname/api/
    // You can set any number of default request options.
    'timeout'  => 2.0,
	'headers' => ['Authorization' => "Basic " .$token, 'Content-Type' => 'application/json', "Accept" => "application/json"],
    //ssl false
    'verify' => false
]); 

Please change Authorization string as per your REST API credentials.The parameters are:

  • $token : This variable will contains authorization string of Elasticsearch rest api.
  • base_uri : The Elasticsearch API host api url path.
  • headers : This will contains request header parameters.
  • timeout : Request timeout in sec.
  • verify : SSL verification false.

We will create json string as like below, we will pass following json data into body of elasticsearch data,

{  
   "search_query":{  
      "size":100000,
      "sort":[  
         {  
            "@timestamp":{  
               "order":"desc",
               "unmapped_type":"boolean"
            }
         }
      ],
      "query":{  
         "filtered":{  
            "query":{  
               "query_string":{  
                  "analyze_wildcard":true,
                  "lowercase_expanded_terms":false,
                  "query":"abc%"
               }
            },
            "filter":{  
               "bool":{  
                  "must":[  
                     {  
                        "range":{  
                           "@timestamp":{  
                              "gte":null,
                              "lte":null
                           }
                        }
                     }
                  ],
                  "must_not":[  

                  ]
               }
            }
         }
      },
      "aggs":{  
         "2":{  
            "date_histogram":{  
               "field":"@timestamp",
               "interval":"30m",
               "pre_zone":"-06:00",
               "pre_zone_adjust_large_interval":true,
               "min_doc_count":0,
               "extended_bounds":{  
                  "min":null,
                  "max":null
               }
            }
         }
      },
      "fields":[  
         "*",
         "_source"
      ]
   },
   "dates":{  
      "search_date":"logstash"
   }
}

We will create json data in php and passed to rest api.

$query_str = 'abc%';
$filter['query_string'] = array('analyze_wildcard' => true, "lowercase_expanded_terms" => false, "query" => $query_str);
      
$query['bool']['must'] = array();
$current_date = date('Y-m-d');
$days_ago = date('Y-m-d', strtotime('-10 days', strtotime($current_date)));
array_push($query['bool']['must'], array('range' => array('@timestamp' => array("gte"=>$stTime, "lte" => $endTime))));
$query['bool']['must_not'] = array();
$params['search_query']['size'] = 100000;
$params['search_query']['sort'] = array();
  array_push($params['search_query']['sort'], array('@timestamp' => array("order"=>"desc", "unmapped_type" => "boolean")));
  
  $params['search_query']['query']['filtered'] = array(
	 "query" => $filter,
	 "filter" => $query
  );
      
$params['search_query']['aggs'] = array(
 "2" => array("date_histogram" => array(
	   "field" => "@timestamp",
	   "interval" => "30m",
	   "pre_zone" => "-06:00",
	   "pre_zone_adjust_large_interval" => true,
	   "min_doc_count" => 0,
	   "extended_bounds" => array("min" =>$stTime , "max" => $endTime),
	)
 )
);
         
$params['search_query']['fields'] = array("*", "_source");
$params['dates']['search_date'] = 'logstash';

$response = $client->get('/_search',[ 'body' => json_encode($params['search_query'])]);
$data = json_decode($response->getBody()->getContents(), true);

			
if(!empty($data['hits'])) {
	if(empty($logs)){
		$logs = $data;
	} else if($data['hits']['total'] > 0) {
		$logs['hits']['total'] = $logs['hits']['total'] + $data['hits']['total'];
		foreach($data['hits']['hits'] as $k =>$hit) {
			array_push($logs['hits']['hits'], $hit);
		}
	
	}
	
}	

I hope you will understand about use of Elastic search api. You can integrate Elasticsearch api using any Programming languages like java,.net,nodejs etc.