How to Integrate Elasticsearch in Laravel: A Complete Guide

integrate elasticsearch in Laravel

Efficient and accurate search capabilities are essential for any modern website. Laravel, one of the best PHP frameworks, offers seamless integration with Elasticsearch to offer distributed search and analytics capabilities.

To help you learn how to leverage your project, we’ll dive into the complete setup process. We’ll check on the operations that Laravel developers perform using Elasticsearch. Plus, the real use case will let you know where and when you can use it on your website. But before that, let’s understand what Elasticsearch is.

What is Elasticsearch?

Elasticsearch is a distributed, open-source search and analytics engine built on top of Apache Lucene. It’s designed to provide fast and relevant search results for large volumes of data. Key features of Elasticsearch include:

  • Full-Text Search: Elasticsearch excels at performing full-text searches on structured and unstructured data. That makes it ideal for building powerful search functionalities.
  • Distributed Architecture: It is designed to work in a distributed environment, meaning it can horizontally scale across multiple nodes or clusters. This enables it to handle vast amounts of data.
  • Real-Time Indexing and Search: It allows you to index and search data almost in real time. That is crucial for sites requiring fast and dynamic data access, such as eCommerce or content management systems.
  • RESTful API: Elasticsearch provides a RESTful API, making it accessible and easy to integrate with various languages and development frameworks.
  • Aggregation: It supports complex aggregations and filtering, allowing users to perform analytics on their data. This feature allows users to calculate statistics or perform data visualizations.
  • Versatility: It’s used in applications such as log and event data analysis, eCommerce product search, and business intelligence.

These features make Elasticsearch a powerful tool for searching, analyzing, and understanding large datasets. Plus, its flexibility, scalability, and real-time capabilities make it a preferred choice by Laravel development experts.

Why use Laravel Elasticsearch?

Using Elasticsearch with Laravel provides numerous benefits for applications that need powerful search and analytics capabilities. Here’s why integrating Elasticsearch with Laravel is a good choice:

  • Simplified API: The Laravel Elasticsearch package provides a simplified API that eliminates the complexity of interacting with Elasticsearch directly. This makes it easier for Laravel developers to implement search and analytics features on their sites.
  • Easy integration with Laravel: The package integrates seamlessly with other Laravel components, such as Eloquent ORM and Blade templating. That makes it easy to incorporate Elasticsearch into your existing Laravel projects.
  • Enhanced search capabilities: Leveraging Elasticsearch, you can implement advanced search features like full-text search, autocomplete, and faceting within your Laravel site.
  • Improved performance: Elasticsearch is known for its speed and scalability, and the Laravel Elasticsearch package helps you leverage it. That provides fast and responsive search experiences to your users.
  • Efficient Full-Text Search: It is optimized for full-text search, providing advanced search features like partial matching, fuzzy searches, and relevance ranking. That makes searching quicker with more relevant results.
  • Custom Search Implementation: With Elasticsearch, developers can implement custom search solutions, such as multi-field searches, faceted search, and geospatial search. That makes Laravel sites offer more advanced search features than traditional SQL databases.

These benefits of Laravel Elasticsearch make it one of the most powerful engines for searching and analytics. By leveraging it effectively, Laravel development company can make your site’s search more responsive, increasing the user experience. Now, you might want to know how to use it, right? So, let’s start with the setup of Laravel Elasticsearch.

Looking to optimize your Laravel site’s search functionality?

How to Setup Laravel Elasticsearch?

Setting up Elasticsearch with Laravel involves multiple steps, from installing Elasticsearch to integrating it into a Laravel project using PHP clients or packages. Here’s a step-by-step guide on how to set up Laravel Elasticsearch:

Step 1: Install Elasticsearch on Your Server or Local Machine

For installation on macOS, you can use Homebrew to install Elasticsearch with the command:

brew tap elastic/tap
brew install elastic/tap/elasticsearch-full
brew services start elastic/tap/elasticsearch-full

To install it on Ubuntu, use the APT package management tool:

sudo apt update
sudo apt install elasticsearch

If you prefer, you can run Elasticsearch in a Docker container to install it on your server or local machine:

docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.9.3

To install Elasticsearch on Windows, you can directly download and install it from the official Elasticsearch website. Once done, start Elasticsearch using the command:

sudo service elasticsearch start

Step 2: Verify Elasticsearch Installation

After installing Elasticsearch, verify it is running by making a request to the local server. Here is the curl command to verify it:

curl http://localhost:9200

After firing this query, you should receive a JSON response confirming that Elasticsearch is running. The response includes the version number and cluster information.

Step 3: Install Elasticsearch PHP Client in Laravel

Laravel needs a PHP client to interact with the Elasticsearch server. The Elasticsearch PHP Client package provides the necessary tools to communicate between your Laravel application and the Elasticsearch instance. To install the client, run the following command in your Laravel project subdirectory:

composer require elasticsearch/elasticsearch

The official PHP client for Elasticsearch is installed, allowing your Laravel site to communicate with the server via the API.

Step 4: Configure Elasticsearch in Laravel

Now that Elasticsearch is installed, you need to configure the connection between Laravel and Elasticsearch. Laravel can manage the connection through the configuration files. Here is the code you need to add in config/services.php file for Elasticsearch:

'elasticsearch' => [
    'hosts' => [
        env('ELASTICSEARCH_HOST', 'localhost:9200'),
    ],
],

Then, in your .env file, define the Elasticsearch host:

ELASTICSEARCH_HOST=localhost:9200

Laravel is now configured to communicate with your local Elasticsearch instance using the host configuration. If you are working in production, update the .env file with your production Elasticsearch host.

Step 5: Create an Elasticsearch Service Class

To interact with Elasticsearch, it’s best to encapsulate the logic into a service class. This service will handle indexing and querying data in Elasticsearch. Here is how to create an ElasticsearchService.php class in your App\Services directory:

use Elasticsearch\ClientBuilder;
class ElasticsearchService
{
    protected $client;
    public function __construct()
    {
        $this->client = ClientBuilder::create()
            ->setHosts([config('services.elasticsearch.hosts')])
            ->build();
    }
    public function search($index, $query)
    {
        $params = [
            'index' => $index,
            'body' => [
                'query' => [
                    'match' => $query
                ]
            ]
        ];
        return $this->client->search($params);
    }
}

This service class allows your Laravel application to search for data by communicating with the Elasticsearch instance. It can be expanded with methods for indexing, updating, and deleting documents.

Step 6: Index Data Automatically with Model Observers

To keep the Elasticsearch index up to date with your Laravel database, you can use Model Observers to automatically index, update, or delete records. To create an observer for the model you want to index in Elasticsearch, e.g., ArticleObserver.php:

use App\Services\ElasticsearchService;
class ArticleObserver
{
    protected $elasticsearch;
    public function __construct(ElasticsearchService $elasticsearch)
    {
        $this->elasticsearch = $elasticsearch;
    }
    public function created(Article $article)
    {
        $this->elasticsearch->index([
            'index' => 'articles',
            'id'    => $article->id,
            'body'  => $article->toArray(),
        ]);
    }
    public function updated(Article $article)
    {
        $this->elasticsearch->index([
            'index' => 'articles',
            'id'    => $article->id,
            'body'  => $article->toArray(),
        ]);
    }
    public function deleted(Article $article)
    {
        $this->elasticsearch->delete([
            'index' => 'articles',
            'id'    => $article->id,
        ]);
    }
}

Attach this observer to the model in AppServiceProvider.php:

Article::observe(ArticleObserver::class);

Now, when records are created, updated, or deleted in your Laravel database, the changes are automatically reflected in Elasticsearch. That will keep your data synchronized.

Step 7: Search Data from Elasticsearch

Now that your data is indexed, you can perform searches. Elasticsearch provides various types of search queries, including full-text searches, match queries, and more. To search for an article, use the ElasticsearchService class:

$results = app(ElasticsearchService::class)->search('articles', ['title' => 'Some title']);

The search method sends a query to Elasticsearch and retrieves the relevant results. You can display or process these results as needed.

Step 8: Test Elasticsearch Setup

Before deploying Elasticsearch, you should test the integration locally to ensure everything works as expected. You can run search queries and check if Elasticsearch returns the correct results. For example:

curl -X GET "localhost:9200/articles/_search?q=title:Some%20title"

If the results are returned based on the search term you provided, your Elasticsearch setup will successfully process search queries. Test a variety of queries and operations like indexing, updating, and deleting to ensure your system works correctly.

Basic Operations with Laravel Elasticsearch Package

When using the Laravel Elasticsearch package (such as the MailerLite Laravel Elasticsearch package), developers can perform a variety of basic operations. It includes indexing, searching, updating, and deleting documents in an Elasticsearch index. Here’s a breakdown of the essential operations using Laravel and Elasticsearch:

Indexing Data

Indexing involves adding new documents to your Elasticsearch index. This is similar to inserting rows into a database table in SQL.

use Elasticsearch\ClientBuilder;
class ElasticsearchService
{
    protected $client;
    public function __construct()
    {
        $this->client = ClientBuilder::create()->build();
    }
    public function indexData($index, $id, $body)
    {
        $params = [
            'index' => $index,
            'id'    => $id,
            'body'  => $body,
        ];
        return $this->client->index($params);
    }
}

Then you can call this method to index data:

$elasticsearchService->indexData('articles', 1, ['title' => 'Introduction to Elasticsearch']);

This will index an article with ID 1 and the title “Introduction to Elasticsearch.”

Search Data

To search data in Elasticsearch, you can use the match query to find documents based on specific fields.

public function searchData($index, $query)
{
    $params = [
        'index' => $index,
        'body' => [
            'query' => [
                'match' => $query,
            ],
        ],
    ];
    return $this->client->search($params);
}

Here is how you can use it:

$results = $elasticsearchService->searchData('articles', ['title' => 'Elasticsearch']);

The above query performs a search in the articles index for articles with titles matching “Elasticsearch”.

Update Documents

You can update existing documents in Elasticsearch using the update API. The document ID is required for this operation.

public function updateData($index, $id, $body)
{
    $params = [
        'index' => $index,
        'id'    => $id,
        'body'  => [
            'doc' => $body,
        ],
    ];
    return $this->client->update($params);
}

To update a document:

$elasticsearchService->updateData('articles', 1, ['title' => 'Updated Elasticsearch Introduction']);

This will update the title of the article with ID 1.

Delete Documents

Deleting a document from an index is straightforward. You need to provide the index name and the document ID.

public function deleteData($index, $id)
{
    $params = [
        'index' => $index,
        'id'    => $id,
    ];
    return $this->client->delete($params);
}
To delete a document:
$elasticsearchService->deleteData('articles', 1);

The above query will delete the document with ID 1 from the articles index.

Bulk Operations

Elasticsearch also supports bulk operations, allowing you to perform multiple actions like indexing, updating, or deleting documents in one request.

public function bulkOperations($operations)
{
    $params = ['body' => $operations];
    return $this->client->bulk($params);
}
Here is the example usage:
$operations = [
    ['index' => ['_index' => 'articles', '_id' => 1]],
    ['title' => 'Bulk Insert Article 1'],
    ['index' => ['_index' => 'articles', '_id' => 2]],
    ['title' => 'Bulk Insert Article 2'],
];
$elasticsearchService->bulkOperations($operations);

This will bulk index two articles in the articles index.

These basic operations provide the foundation for interacting with Elasticsearch in a Laravel application. By using methods like index, search, update, and delete, professional Laravel developers can build robust search functionalities.

Real-World Use Cases of Laravel Elasticsearch

Laravel Elasticsearch is commonly used in real-world applications to enhance search functionality. Below are several real-world use cases of using Elasticsearch in Laravel-based website:

eCommerce Search Optimization

In an eCommerce platform, Elasticsearch is used to provide fast, accurate, and scalable product searches. Features like full-text search, faceted search, filtering, and real-time auto-suggestions can improve user experience.

Example Use Case:

  • Product Catalog Search: Elasticsearch indexes products with fields like name, description, tags, category, and price. When a user types a query, Elasticsearch delivers results with filters for price ranges, categories, and other metadata.
  • Autocomplete: It enables autocomplete suggestions for search terms while users are typing, improving user experience.

Blog or News Websites for Full-Text Search

News or blog websites with large article libraries use Elasticsearch to allow users to search content quickly and accurately. Elasticsearch’s full-text search capabilities allow for more relevant search results by also matching for semantic relationships within the text.

Example Use Case:

  • Article Search: Blog and media websites index all content (titles, bodies, tags, and metadata) in Elasticsearch. Users can search articles based on keywords, and Elasticsearch can deliver results ranked by relevance.
  • Search Filtering: Elasticsearch can filter articles by date, category, author, or tags to refine results.

Social Media or Forum Platforms

On platforms like social media or forums, where user-generated content grows rapidly, Elasticsearch is critical. It is used to enhance the platform’s ability to find posts, group discussions, or related topics. That makes large-scale queries manageable.

Example Use Case:

  • Search Posts and Comments: Index posts and comments in real-time using Laravel observers. Elasticsearch can then search through the entire content pool for relevant keywords.
  • User Search: Users can be indexed to support features like finding other members, follower counts, or user-generated content within the platform.

Geospatial Search for Location-Based Applications

Elasticsearch supports geospatial queries, making it useful for applications where location-based searches are crucial. This is especially beneficial for platforms that offer location-based services like restaurant finders, hotel bookings, and event listings.

Example Use Case:

  • Local Business Search: Elasticsearch can index business data along with latitude and longitude. Users can then search for businesses within a specific distance or location (e.g., “restaurants near me”).
  • Event Search by Location: Elasticsearch allows filtering of events by location, date, and type, delivering location-based results quickly.

Real-Time Analytics and Monitoring Applications

Elasticsearch is used to store and search logs or analytical data in real-time. Sites with large-scale logging can push their log data to Elasticsearch and retrieve it efficiently for monitoring.

Example Use Case:

  • Application Logging: Laravel applications can send logs to Elasticsearch, which makes it easier to search, filter, and analyze logs.
  • Real-Time Data Monitoring: Elasticsearch can be used in dashboards to monitor website traffic, server performance, and user interactions.

These use cases show us the importance of Elasticsearch in real-world web applications. That’s why Laravel development services prefer to use Elasticsearch as a search and analytical solution on their website.

FAQs About Laravel Elasticsearch

What is Elasticsearch best used for?
Elasticsearch is best used for applications that require fast and efficient full-text search and real-time analytics. It's particularly well-suited for use cases such as eCommerce, content management systems, social media, and analytics.
Can Elasticsearch replace SQL?
No, Elasticsearch cannot fully replace SQL databases. While it's excellent for search and analytics, SQL databases are still essential for structured data storage, relational operations, and transactions. Elasticsearch can complement SQL databases by providing efficient search and analytics capabilities.
What does Elasticsearch provide?
Elasticsearch provides a distributed search and analytics engine that can handle large volumes of data and provide fast and relevant search results. It offers features such as full-text search, real-time analytics, geolocation search, and aggregation capabilities.

Final Thoughts

Laravel Elasticsearch provides a powerful and flexible solution for implementing efficient search capabilities. By leveraging the robust features of Elasticsearch, you can enhance user experience and improve data accessibility.

Implementing Laravel Elasticsearch starts with installing it on a local machine or server and ends with finally testing if it’s working. Once you are done with the setup, you can perform operations like index, search, update, and delete. These operations can be implemented in real-world scenarios for eCommerce search optimization, real-time analytics, and more.

If you want to enhance your site’s search functionality and enhance user experience with such tools, hire Laravel developers.

Want to build a robust and well-designed Laravel site?

author
Chinmay Pandya is an accomplished tech enthusiast specializing in PHP, WordPress, and Laravel. With a solid background in web development, he brings expertise in crafting innovative solutions and optimizing performance for various projects.

Leave a comment