
Elasticsearch is an open-source search server based on Apache Lucene. ElasticSearch in Codeigniter enables you to perform super quick full-text and other complex searches. It also incorporates a REST API which allows you to effortlessly issue requests for creating, deleting, overhauling, and recovering information.
Adding elasticsearch to CodeIgniter projects is fairly simple.
- Setup the Environment
- Handle Calls through CURL
- Create the Index
- Get the Status
- Count Existing Indexes
- Set Mapping for Index
- Delete an Index
- Make a Search Query
- Make a Search Query with Result Sized Set
- To Get Index Through ID
- Get the Whole Server
- Get Similar Indexes for a Index ID
- Make a Search Query with Results Sized Set
- Create a Query based on Similar Terms
- Use Advanced Query
- Final Words
Setup the Environment
The first step of using elasticsearch in CodeIgniter projects is the setting up of an environment on hosting for PHP. This involves constructing the right settings and setting up the configuration variable.
For this, use the following elasticsearch class:
For this, use the following elasticsearch class:
class ElasticSearch { public $index; public function __construct() { $ci = &get_instance(); $ci -> config -> load("elasticsearch"); $this -> server = $ci -> config -> item('es_server'); $this -> index = $ci -> config -> item('index'); }
Handle Calls through CURL
Once the elasticsearch is up and running, it is time to handle the calls through CURL. For this use a private function named call.
To handle call for every function by using curl
private function call($path, $method = 'GET', $data = null) { if (!$this -> index) { throw new Exception('$this->index needs a value'); } $url = $this -> server . '/' . $this -> index . '/' . $path; $headers = array('Accept: application/json', 'Content-Type: application/json', ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); switch($method) { case 'GET' : break; case 'POST' : curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); break; case 'PUT' : curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); break; case 'DELETE' : curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; } $response = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); return json_decode($response, true); }
You might also like: How To Setup Elasticsearch With MySQL
Create the Index
Creating the indexes for optimizing the searches is an essential requirement for many projects. To create the index with null validation mapping, use the following function:
public function create($map = false) { if (!$map) { $this -> call(null, 'PUT'); } else { $this -> call(null, 'PUT', $map); } }
Get the Status
Getting the status of the calls is a simple matter of using the following function:
public function status() { return $this -> call('_status'); }
Count Existing Indexes
Counting the existing indexes is simple. Just use the following code snippet:
public function count($type) { return $this -> call($type . '/_count?' . http_build_query(array(null => '{matchAll:{}}'))); }
Set Mapping for Index
Use the following function for setting up mapping for the index:
public function map($type, $data) { return $this -> call($type . '/_mapping', 'PUT', $data); } public function add($type, $id, $data) { return $this -> call($type . '/' . $id, 'PUT', $data); }
Delete an Index
Use the following code snippet to delete an index:
public function delete($type, $id) { return $this -> call($type . '/' . $id, 'DELETE'); }
Stop Wasting Time on Servers
Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.
Make a Search Query
Setting up a simple search query is easy. Just use the following code snippet in the project’s code:
public function query($type, $q) { return $this -> call($type . '/_search?' . http_build_query(array('q' => $q))); }
To setup an advanced search query that uses JSON data use the following code snippet:
public function advancedquery($type, $query) { return $this -> call($type . '/_search', 'POST', $query); }
Make a Search Query with Result Sized Set
Use the following code snippet to set up a search query with a result sized set:
public function query_wresultSize($type, $query, $size = 999) { return $this -> call($type . '/_search?' . http_build_query(array('q' => $q, 'size' => $size))); }
To Get Index Through ID
Get the index through the ID using the following snippet:
public function get($type, $id) { return $this -> call($type . '/' . $id, 'GET'); }
Get the Whole Server
The following code snippet gets the entire server:
public function query_all($query) { return $this -> call('_search?' . http_build_query(array('q' => $query))); }
Get Similar Indexes for a Index ID
It is easy to get all similar indexes that matches a particular index ID. USe the following code snippet:
public function morelikethis($type, $id, $fields = false, $data = false) { if ($data != false && !$fields) { return $this -> call($type . '/' . $id . '/_mlt', 'GET', $data); } else if ($data != false && $fields != false) { return $this -> call($type . '/' . $id . '/_mlt?' . $fields, 'POST', $data); } else if (!$fields) { return $this -> call($type . '/' . $id . '/_mlt'); } else { return $this -> call($type . '/' . $id . '/_mlt?' . $fields); } }
Make a Search Query with Results Sized Set
Creating a query with results sized set is a simple matter of using the following code snippet:
public function query_all_wresultSize($query, $size = 999) { return $this -> call('_search?' . http_build_query(array('q' => $query, 'size' => $size))); }
Create a Query based on Similar Terms
Use the following code snippet to set up a query based on similar terms. Put the code in elasticsearch.php under application/libraries/
public function suggest($query) { return $this -> call('_suggest', 'POST', $query); } }
Use Advanced Query
Use the following code snippet for using advanced query. Put the snippet in the view file:
$esquery = '{ "fields" : ["name","urlid","country", "country_name"], "query": { "query_string": { "query":"'.$query.'" } } }'; echo json_encode(($this->elasticsearch->advancedquery("station",$esquery)));
Final Words
Elasticsearch in CodeIgniter adds great power to projects. Remember that Elasticsearch is a huge library with a number of use cases. It is essential that the developers should study the documentation of the library for more to-the-point integration of Elasticsearch into CodeIgniter projects.
Shahzeb Ahmed
Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]