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 Setup Elasticsearch with Laravel 8.x

Updated on March 28, 2022

4 Min Read
elasticsearch php

Elasticsearch is an open search and analytics engine for printed, numerical, geospatial, organized, and unstructured information. Elasticsearch is built on Apache Lucene. Known for its basic REST APIs, distributed nature, speed, and adaptability, Elasticsearch is the central component of the Flexible Stack, a set of free and open tools for information ingestion, enhancement, capacity, examination, and visualization.

Elasticsearch is a server based tool that is capable of full-text searching at very high speed. It is powered by Apache Lucene (which is an open source full text search library). It is able to achieve this speed because instead of searching the whole word matching the desired result from the whole database, it uses indexing.

This is similar to the indexing of a book. In this case, indexes are made out of letters. So, as soon as you start searching, the Elasticsearch mechanism starts hovering over your result matching your first letter entries.

What is Elasticsearch in Laravel

Elasticsearch is a real-time, distributed, and open-source full-text search and analytics engine. It is used in Single Page Application ventures. Elasticsearch is created in Java and used by numerous enormous organizations around the world. It is authorized under the Apache permit adaptation 2.0.

Elasticsearch with Laravel allows you to store, search, and analyze large volumes of information rapidly, in real-time, and provides answers in milliseconds. In spite of the fact that it’s extremely effective with deltas and querying data isn’t that simple. It’s able to realize fast search reactions because rather than looking at the content specifically, it looks at the index.

How Do I Set It Up?

We will learn in this little tutorial about how we can setup Elasticsearch with our Laravel App. We will see some basic examples and will start working with them. I would love it if you follow the guide side by side so you can make changes accordingly for better learning.

Prerequisites:

  •   You have an activated server on Cloudways. Click here to launch one.
  •   You have an active Laravel App installed on your server.
  •   You have installed Elasticsearch on your Cloudways Server. If not click here to see the related guide.

Step 1:  Checking Elasticsearch Installation

Open up SSH terminal and enter the following command:

$ curl -XGET 127.0.0.1:9200

Step 2: Installing Elasticsearch Client for PHP Laravel

$ composer require elasticsearch/elasticsearch

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Let’s make some changes in our routes.php and see if we can check our client installation.

$ vim /public_html/app/Http/routes.php

Now edit a route:

Route::get('/', function () {   
        $client = Elasticsearch\ClientBuilder::create()->build();
        var_dump($client);
});

Now browse your app and You will see something like this:

object(Elasticsearch\Client)[163]
  public 'transport' => 
    object(Elasticsearch\Transport)[161]
      public 'connectionPool' => 
        object(Elasticsearch\ConnectionPool\StaticNoPingConnectionPool)[160]
          private 'pingTimeout' => int 60
          private 'maxPingTimeout' => int 3600
          protected 'connections' => 
            array (size=1)
              ...
          protected 'seedConnections' => 
            array (size=1)
              ...
          protected 'selector' => 
            object(Elasticsearch\ConnectionPool\Selectors\RoundRobinSelector)[157]
              ...
          protected 'connectionFactory' => 
            object(Elasticsearch\Connections\ConnectionFactory)[156]
              ...
          public 'connectionPoolParams' => 
            array (size=1)

Now let’s see how can we inject into our Elasticsearch:

Route::get('/enter/{age}/{name}',function($age,$name){
$client = Elasticsearch\ClientBuilder::create()->build();	//connect with the client
$params = array();
$params['body']  = array(	
  'name' => $name, 											//preparing structred data
  'age' => $age
  
);
$params['index'] = 'BeyBlade';
$params['type']  = 'BeyBlade_Owner';
$result = $client->index($params);							//using Index() function to inject the data
var_dump($result);
});

Now get into your browser:

<your_laravel_app_url>/enter/23/HarryPotter
<your_laravel_app_url>/enter/22/RonWeasley
<your_laravel_app_url>/enter/21/Harmoine

This will give you a result which is something like this:

array (size=5)
  '_index' => string 'BeyBlade' (length=7)
  '_type' => string 'BeyBlade_Owner' (length=15)
  '_id' => string 'AVQujnHkGBg9fUGgzM5T' (length=20)
  '_version' => int 1
  'created' => boolean true

Now let’s pull the data out using search queries. We will make a new route and will try finding our results by giving the input age:

Route::get('find/{age}',function($age){
$client = Elasticsearch\ClientBuilder::create()->build();		//connect to the client
$params['index'] = 'BeyBlade';						// Preparing Indexed Data
$params['type'] = 'BeyBlade_Owner';								
$params['body']['query']['match']['age'] = $age;			//Find data in which age matches given input
$result = $client->search($params);					//Using Search function
return($result);	               					//Printing out result
});

Now go to your browser and type:

<your_laravel_app_url>/find/23

You will get something like this:

{"took":3,"timed_out":false,"_shards":
        {"total":5,"successful":5,"failed":0},
        "hits":
            {"total":1,"max_score":0.30685282,
              "hits":[{"_index":"BeyBlade",
             "_type":"BeyBlade_Owner",
               "_id":"AVQtylPFGBg9fUGgzM5M",
            "_score":0.30685282,
           "_source":{"name":"HarryPotter","age":"23","badges":8}}]}}

There you go, you have configured your Laravel app with Elasticsearch.

Cloudways provides the most optimized Managed Laravel Hosting experience in the cloud industry. Elasticsearch is also available on the platform. Combined with 24/7 Live Chat support, you can host your PHP web apps on the best infrastructure and avail Elasticsearch.

Conclusion

As Elasticsearch is built on top of Lucene, it exceeds expectations at a full-text search in addition to being fast. Elasticsearch allows users to scale out to hundreds or even thousands of servers, and handle petabytes of information. As a result, Elasticsearch is well suited for time-sensitive, used cases such as security analytics and framework monitoring.

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]

Noor Ali

Noor Ali is an Associate Software Engineer at Cloudways. He loves to solve technical problems through programming and mathematics.

×

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!