Tag Archives: #php

Installing Elasticsearch Client on PHP

For a simple demonstration of using Elasticsearch programmatically as a web app, it’s a little more practical to use PHP as a starting point to learn how to connect and display search results. As a guideline, the quick-start instruction from Elastic site is a starting point. To expand (possibly complete) the out of the box setup, below are the steps to setup PHP to enable Elasticsearch support.

First, install the PHP Curl support for Apache on Linux:

apt-get -y install php-curl

Setup the PHP Composer in the doc-root folder, as outlined from elasticsearch-php github. Setup the php libraries via Composer:

php composer.phar init
curl -s http://getcomposer.org/installer | php
php composer.phar install --no-dev

Be sure to get the dependency package “elasticsearch/elasticsearch” and use the latest version as default. Note, skip the development package as it’s not really necessary.

Then, edit the composer.json file to include the directive:

   "require": {
            "elasticsearch/elasticsearch": "~6.0"

Finally, create a test page to see if it can connect to the Elasticsearch server:


require 'vendor/autoload.php';

use Elasticsearch\ClientBuilder;

$hosts = [

$client = ClientBuilder::create()

$params = [
    'index' => 'myindexname',
    'body' => [
        'query' => [
            'match' => [
                'post_title' => 'elasticsearch'

$response = $client->search($params);

$totalhits = $response['hits']['total'];
echo "We have $totalhits total hits\n";

echo "<P>The hits are the following:</P>";
$result = null;
while ($i <= $totalhits)
        $result[$i] = $response['hits']['hits'][$i]['_source'];

foreach ($result as $key => $value)
        echo $value['post_title'], "<br>";


Output will look something like this:

We have 2 total hits

The hits are the following:

Using Elasticsearch for JBOSS Logs
Deleting Entries in Elasticsearch Based On Timestamp

Update Nov/2019: Since Elasticsearch updated their basic license to include basic username/password security, it’s advisable to set them up. It’s a straight-forward addition:

$hosts = [
      'host' => 'myelasticsearchhost',
      'port' => '9200',
      'scheme' => 'http',
      'user' => 'myElasticUser',
      'pass' => 'myPassword'