Elastic Search PHP: A Simple Guide


Elastic Search is an Open-Source full text search based on Apache Lucene. This search engine allows you to store, search super-fast full-text and perform other complex searches. It also includes a built-in REST API that facilitates us to issue requests for

  • Creating
  • Deleting
  • Updating and
  • Retrieves data.

You can search for long phrases. Depending on the elastic search’s database it will retrieve and give you the results within seconds.

Functionalities:

  • Mapping the REST API with other language clients.
  • Discovering the cluster nodes and automatically configures it.
  • Persistent, Keep-Alive connections within the lifetime of the script.
  • Balancing the loadagainst all available nodeswith pluggable selection strategy.
  • Defaults to round-robin.
  • Offersmultiple connection strategies via pluggable connection pools.
  • Generalized, pluggable architecture – most components can be replaced with your own custom class if specialized behavior is required.
  • Option to use asynchronous future, which enables parallel execution of curl requests to multiple nodes.

Installing Elastic Search for PHP:

Include elasticsearch/elasticsearch as a dependency in your project’s composer.json file

{

“require”: {

“elasticsearch/elasticsearch”: “~2.0”

}

}

Getting data from Elasticsearch:

Now replace the code with the following in your index.php and run it

<?php

require ‘vendor/autoload.php’;

$client = Elasticsearch\ClientBuilder::create()->build();

$params = [

‘index’ => ‘my_index’,

‘type’ => ‘my_type’,

‘id’ => ‘my_id’,

];

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

echo $response[‘_source’][‘first field’];

Searching in Elasticsearch:

<?php

require ‘vendor/autoload.php’;

$client = Elasticsearch\ClientBuilder::create()->build();

$params = [

‘index’ => ‘my_index’,

‘type’ => ‘my_type’,

‘body’ => [

‘query’ => [

‘match’ => [

‘first field’ => ‘first fiel’

],

],

],

];

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

$hits = count($response[‘hits’][‘hits’]);

$result = null;

$i = 0;

while ($i< $hits) {

$result[$i] = $response[‘hits’][‘hits’][$i][‘_source’];

$i++;

}

foreach ($result as $key => $value) {

echo $value[‘first field’] . “<br>”;

}

Version Requirement:

Version 5.0 of this library requires at least PHP version 5.6.6 to function. In addition, it requires the native JSON extension to be version 1.3.7 or higher.

Elastic search engine outputs results faster than SQL and is one of the most used searches around the web.

In this post you have learned how to connect Elastic search with PHP and how to get and search data from it. Please check out our blogs for technology related queries.

+ There are no comments

Add yours