This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

How to use Elasticsearch Codeigniter Library in your projects

September 30, 2021

4 Min Read
codeigniter elasticsearch

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

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.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Cloudways hosting has one of the best customer service and hosting speed”

Sanjit C [Website Developer]

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 [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

x

For 4 Months

Promo: BFCM2021
  • 28

days

  • 28

Hours

  • 28

Mins

  • 28

Secs