Install & Configure Elastic Search in Laravel
Jan
16
2020
16 Jan 2020

How to Install and Configure Elasticsearch in Laravel?

What is Elastic Search? A basic understanding

Search is one of the most important functionalities in any application. Using “LIKE” in query is the most common query being used but when as your application size grows “LIKE” becomes an overhead and the speed of your application drains out. This is when the tools like Elasticsearch comes in handy and helps in making your application robust.

After all the collection, aggregation, visualization, enrichment is done, Elastic Search enables its functionality: indexing, search. Elasticsearch provides real-time search and analytics for all types of data. Whether you have structured or unstructured text, numerical data, or geospatial data, Elasticsearch can efficiently store and index it in a way that supports fast searches. You can go far beyond simple data retrieval and aggregate information to discover trends and patterns in your data. And as your data and query volume grows, the distributed nature of Elasticsearch enables your deployment to grow seamlessly right along with it. While not every problem is a search problem, Elasticsearch offers speed and flexibility to handle data in a wide variety of use cases:

  • Add a search box to an app or website
  • Store and analyze logs, metrics, and security event data
  • Use machine learning to automatically model the behaviour of your data in real-time
  • Automate business workflows using Elasticsearch as a storage engine
  • Manage, integrate, and analyze spatial information using Elasticsearch as a geographic information system (GIS)
  • Store and process genetic data using Elasticsearch as a bioinformatics research tool

How to perform integration with Laravel?

To install the elastic search in Laravel, you need to add the following packages in it.

composer require laravel/scout
composer require tamayo/laravel-scout-elastic
composer require elasticsearch/elasticsearch

After that update your composer and the add the following in the Service Providers Array.

Laravel\Scout\ScoutServiceProvider::class,
ScoutEngines\Elasticsearch\ElasticsearchProvider::class,

Example:
Inside your model add the Laravel Scout Searchable Trait as below:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Account extends Model
{
     use Searchable;
     protected $fillable = [
        'name'
     ];
     public function user(){
        return $this->belongsTo('App\User');
     }
}

If you want to customize searchable array then add in tour model file

     /**
     * Get the indexable data array for the model.
     *
     * @return array
     */
    public function toSearchableArray()
    {
        $array = $this->toArray();

        // Customize array...

        return $array;
    }

Now, navigate to config/scout.php and change this line:

'driver' => env('SCOUT_DRIVER', 'algolia'),

to this:

'driver' => env('SCOUT_DRIVER', 'elasticsearch'),

If you scroll down on that same page, you should see some driver configurations for Algolia and ElasticSearch, the ES one should look like this:

elasticsearch' => [
  'index' => env('ELASTICSEARCH_INDEX', 'laravel'),
  'config' => [
                'hosts' => [ env('ELASTICSEARCH_HOST', 'localhost') ]
              ],
   ],

If it’s not there, you can just add the snippet from above.
Next, go to your .env file and add configuration settings for Elasticsearch:

ELASTICSEARCH_INDEX=scout
ELASTICSEARCH_HOST=http://localhost:9200

Note: If you do not have a scout.php file inside your config folder, you can create one yourself and copy the contents from vendor/laravel/scout/config/scout.php (and obviously changing to the configuration to as stated above).

Now, you need to import the model you wish to search via scout.
Inside your terminal/command line, type:

php artisan scout:import "App\Account"

*remember to change the “App\Account” to the model you are using*

You should see a success message that tells you how many records it has returned.
Now to test if this is all working correctly, run:

php artisan tinker

App/Account::search('literallyanytextyouwantosearch')->get();

If working correctly, it will return arrays of matching results in JSON format.
Now, you’ll need to create a search controller,

php artisan make:controller SearchController

Now, navigate to that file inside your text editor, and include your model namespace:

use App\Account;

Then create a method inside the SearchController, like so:

public function search(Request $request){
  if($request->has('search')){ 
     $accounts = Account::search($request->input('search'))->get();
  }
  return view('search.results', compact('accounts'));
}

Then navigate to your web.php file and add the following route:

Route::get('/SearchQuery', '[email protected]');

Now your backend setup is complete.
NOTE:

1. If you want to show all index then run following URL

http://localhost:9200/scout/_search?q=*

2. If you want to show specific search index

http://localhost:9200/scout/_search?q={your_search text}

ex:http://localhost:9200/scout/_search?q=mobile

3. Start/Stop elastic search command:

Start :

sudo /bin/systemctl daemon-reload
sudo /bin/systemctl enable elasticsearch.service
sudo systemctl start elasticsearch.service

Stop:

sudo systemctl stop elasticsearch.service

For init:
Start :

sudo -i service elasticsearch start

Stop:

sudo -i service elasticsearch stop