Home/How to use Elastic Search with PHP – Tutorial

How to use Elastic Search with PHP – Tutorial

Published On: 29 April 2015.By .
  • Product & platform Engineering

Searching is an important part of many application but it can be painful if you have to deal with large database. Recently I got to work with Elastic Search, a very efficient search tool that provides lots of developer friendly functionality. I have created my own class to integrate it with PHP. You can install Elastic search for php and find detailed document with the help of below links.
http://www.elastic.co/guide/en/elasticsearch/client/php-api/master/_installation_2.html
https://github.com/elastic/elasticsearch-php

PHP tutorials Auriga IT

In this class I have write functions to insert, update and delete data in Elastic search using bulk operation. I will update it will search functionality very soon.

require 'vendor/autoload.php';	//autoload.php from elastic-search
class ElasticSearch
{
private $_client;
	 
	public function __construct(){
		if ($this->_client === NULL)
			$this->connect();
		return $this->_client;
	} 
	 
	 /**
	 * Initialize Elastic Search Object 
	 */
	public function connect()
	{
		$params = array();
		$params['hosts']=array('HOST_NAME:PORT');
$params['connectionParams']['auth']=array('USERNAME','PASSWORD','Basic');
		
$this->_client = new Elasticsearch\Client($params);
	}
	
	public function getInstance()
	{
		return $this->_client;
	}
	
	
/**
	 * Update already existing data in elastic search.
	 * We can update date for multiple ids.	
	 * Data format must be like as below
	 * $params will contain ‘inedx’ and ‘type’ parameter for data to be updated.
	 * $data=array(
		       _id1=>array(
				'field1'=>'value1',
				'field2'=>'value2',
			 	 ...
				),
			 _id2=> array(
				'field1'=>'value1',
				'field2'=>'value2',
			 	 ...
				),
			   ...	
			   );
	 * 	 _id => updateArray
	 */
	public function updateData($data,$params)
	{
	  try {
		if(!isset($params['index']) || !isset($params['type']))
			die("Unable to update Elastic. Either index or type is not defined");
		
		$client = $this->_client;
		
		foreach ($data as $_id => $update) 
		{
			$params['body'][] = array(
        		'update' => array(
            		'_id' => $_id
        		)
    		);
			
			$params['body'][] = array(
        		'doc_as_upsert' => 'true',
        		'doc' => $update
    		);
			
		}
		$responses = $client->bulk($params);
	  }
	  catch(exception $e)
	  {
			//die($e->getMessage());
	  }
	}

	
	/**
* Add data in elastic search
* $data format must be same as in previous function (i.e.  _id=insertArray)
       *  @param array() $data :- data to be inserted
	*  @param array() $params:- contains index and type information
	*  @return Add Provided data to Elastic search document for given Listing and type
	 */
	public function addElasticData($data, $params)
	{
	  try{
		if(!isset($params['index']) || !isset($params['type']))
			die("Unable to update Elastic. Either index or type is not defined");
		
		$client = $this->_client;
		foreach ($data as $_id => $insert)
		{
    		$params['body'][] = array(
        		'index' => array(
            	'_id' => $_id
        	)
    	  );
		  $params['body'][] = $insert;
		}
		$responses = $client->bulk($params);
		return $responses;
		}
	  catch(Exception $e){
			//die($e->getMessage());
	  }
	}
	
	/**
	 * This function will delete all data for given Index and Type in Elastic search
	 */
	public function deleteElastic($params)
	{
	  if(!isset($params['index']) || !isset($params['type']))
		die("Unable to delete data. Either index or type is not defined");
	  try{
	  	$client = $this->_client;
		unset($params['type']);
		$client->indices()->delete($params);
  }
	  catch (Exception $e) {
			//die($e->getMessage());
	  }
	}	
}

Related content

We Love Conversations

Say Hello
Go to Top