Laravel

Laravel Elasticsearch Tutorial – The Complete Guide

February 27, 2018

author:

Laravel Elasticsearch Tutorial – The Complete Guide

Elastic Search performs real-time distributed search and analysis. In short, it is a platform or engine that performs a full-text search. It has a growing popularity over the years. It has powerful features and is easy to configure and uses RESTful API.

# Getting Familiar with Elasticsearch

Most of the people compare Elasticsearch with SQL for understanding. But at times, it only raises more doubts and misconceptions. There is no real to Relational database concepts into this. Let us try and understand the Elasticsearch basics in its pure form:

Documents:

Elasticsearch is schema-free data storing system. Elasticserach doesn’t indulge in database or table storage. It uses JSON formatted documents. All the operations like search, filler, sort are performed on this documents.

Index:

To perform search and other operations, Elasticsearch indexes the documents. It logically maps the data keys (or fields) together in documents that have similar structure. For instance, an index for users, posts, comments, etc. can be created separately.

Type:

Within the index, there are data types. The index usually carries one type, but we can add multiple types as and when required. It helps in faster-searching capabilities. Yet, types are critical, the same key (or field) must not hold multiple data types. Ignorance of this can lead to faulty search or unexpected results.

# Installing Prerequisites

To use Elasticsearch in Laravel, we need to first install Elasticsearch separately on our machine. Since most of the Laravel application is build on Homestead environment by Vagrant, we will install stuff keeping that in mind. So here’s what you need:

• Linux Ubuntu Environment (viz. Homestead already has that)
• Oracle JDK 8 (we will install in the next step)

# Install Java SDK

Here are the steps to install the official Oracle SDK:

• Install Oracle’s PPA

sudo add-apt-repository ppa:webupd8team/java

• Also, update the package repository

sudo apt-get update

• Install the stable version of Java. For this post, we will install version 8:

sudo apt-get install oracle-java8-installer

• Once installed, confirm the version:

java -version

If you see the version display, it implies that the installation was successfully completed.

# Download & Install in Ubuntu

You can, of course, download the zip, tar, etc. package directly from the official website, but for Ubuntu, let us use CMD, it will install everything with simple commands.

1. First of all, update the package index:

sudo apt-get update

2. Also, download the latest version of Elasticsearch (2.3.1 as of writing this post) in de format:

wget https://download.elastic.co/elasticsearch/release/org/elasticsearch/distribution/deb/elasticsearch/2.3.1/elasticsearch-2.3.1.deb

3. And install it using dpkg:

sudo dpkg -i elasticsearch-2.3.1.deb

This installs Elasticsearch in /usr/share/elasticsearch/ and configuration files are placed in /etc/elasticsearch. Also /etc/init.d/elasticsearch stores init scripts.

4. To let Elasticsearch start and stop automatically, let us also add init script to the default runlevels.

sudo systemctl enable elasticsearch.service

# Configure Elasticsearch

We need to customize node.name and cluster.name in elasticsearch.yml file. They enable auto-discovery that automatically discovers and maps nodes to a cluster. It may lead to unexpected result if we don’t configure them. So let us go ahead and do that. Open the file any of your favorite text editor. We will edit it with nano:

sudo nano /etc/elasticsearch/elasticsearch.yml

Firstly, Uncomment cluster.name and node.name by removing the # character and update them as per your conveyance. For instance,

cluster.name: "my-application"
node.name: "node-1"

# Start Elasticsearch

Start Elasticsearch:

sudo systemctl start elasticsearch

Check the status:

systemctl status elasticsearch.service
Installing Elasticsearch for Laravel, Check status

This should start elasticsearch on port 9200, test it with the curl request with a simple GET request.

curl -X GET 'http://localhost:9200'
Installing Elasticsearch for Laravel, CURL Reqeust

# Elasticsearch in Laravel

And its finally the moment we have been waiting for. I understand we have come a long way before we would actually integrate elasticsearch with Laravel application but unfortunately that’s the boring part of installing any new platform or service.

And ironically, to integrate Laravel with Elasticsearch, we only need a single package that means a simple composer command:

# composer.json
"cviebrock/laravel-elasticsearch": "^1.2"
composer update

Now, publish the config file:

php artisan vendor:publish
Install laravel package for Elasticsearch

# Elasticsearch  Security

Though Elasticsearch doesn’t have any built-in security and anyone who has access to it can control it, this isn’t really risky. This is because Elasticsearch typically listens on loop-back interface like 127.0.01 which obviously is available only locally. Hence public access is restricted by default and serves the security purpose well provided the node (server) users are trustworthy.

# Usage of Elasticsearch in Laravel

Here’s an instance of __

$data = [
    'body' => [
        'tags' => $tags,
        'name' => $shot['name'],
    ],
    'index' => 'my_index',
    'type' => 'my_type',
    'id' => $shot['id'],
];
$return = \Elasticsearch::index($data);

You can fetch data with:

$params = Input::all();
$keyword = $params['term'];
$query = [
    'multi_match' => [
        'query' => $keyword,
        'fields' => ['tags'],
    ],
];
$parameters = [
    'index' => 'my_index',
    'type' => 'my_type',
    'body' => [
        'query' => $query,
        "from" => 0,
        "size" => 15,
    ]
];
$response = \Elasticsearch::search($parameters);

# Uninstalling Elasticsearch

Many developers face issues while uninstalling Elasticsearch from their Ubuntu system. Here’s a safe way to do that:

Remove ElasticSearch

sudo apt-get --purge autoremove elasticsearch

Remove ElasticSearch Directories

sudo rm -rf /var/lib/elasticsearch/
sudo rm -rf /etc/elasticsearch

Conclusion:

This post may have overwhelmed many developers who aren’t familiar with Elasticsearch or its installation. Initially, it did have some boring stuff like running random commands, but I tried to make it knowledgeable and informative so that you don’t face any clutters in the future. As the post progressed, we configured Elasticsearch specific settings and discovered commands to start its service. We also stopped by to talk about its security features.

And after all these hassles, we installed a package to integrate Elasticsearch with Laravel and saw its basic usage. In the end, we completed the Elasticsearch cycle with an overview to uninstall it from the system.

Questions & Comments:

All I hope is a fruitful tutorial for you and save you from running random issues. Yet, incase you face errors while following any step, reach out to us in the comment section below.

Leave a comment

Your email address will not be published. Required fields are marked *