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:

<?php

require 'vendor/autoload.php';

use Elasticsearch\ClientBuilder;

$hosts = [
   'http://myelasticsearchhost:9200'
];

$client = ClientBuilder::create()
   ->setHosts($hosts)
   ->build();

$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;
$i=0;
while ($i <= $totalhits)
{
        $result[$i] = $response['hits']['hits'][$i]['_source'];
        $i++;
}

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

Leave a Reply

Your email address will not be published. Required fields are marked *