X
    Categories: Learn CodeIgniter Tutorials, Tips And GuidesLearn PHP Tutorials, Tips And Guides
Reading Time: 4 minutes

Elasticsearch is a popular text search engine that has recently become very popular with PHP developers. It is a popular choice for adding real-time data processing capabilities.

Adding elasticsearch to CodeIgniter projects is simple enough.

You might also like: How To Host CodeIgniter On Cloud Using SSH

Setup the Environment

The first step of using elasticsearch in CodeIgniter projects is the setting up the environment. This involves constructing the right settings and setting up the configuration variable.

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 requirements for many projects. To create 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');

}

Make a Search Query

Setting up a simple search query is quite simple. 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 for setting 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 adds great power to CodeIgniter 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.

Owais Alam :is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at owais.alam@cloudways.com