Laravel and Elasticsearch Pure and Types of Query

Mohammad Roshandelpoor
5 min readApr 26, 2024

a powerful search engine can make or break the user experience. Elasticsearch, a versatile and fast search server, is a popular choice for developers seeking to enhance the search capabilities of their web applications. This article will guide you on integrating Elasticsearch with Laravel, a popular PHP framework, to create a robust and efficient search engine for your applications.

What is Elasticsearch?

Elasticsearch is an open-source, distributed, RESTful search and analytics engine. It is built on Apache Lucene, a powerful search library, and is known for its speed, scalability, and ability to execute complex queries in real-time. Elasticsearch is often used for log and event data analysis, full-text search, and as a component of a monitoring system.

Elasticsearch organizes data in a hierarchical structure — clusters, indices, and documents. It communicates through HTTP and uses a schema-free JSON (JavaScript Object Notation) as a data format.

Elasticsearch and Laravel: A Perfect Match

Elasticsearch and Laravel can work together to create powerful web applications with efficient search functionalities. Elasticsearch’s speed and scalability combined with Laravel’s expressive syntax make it a popular choice among PHP developers.

The main advantage of this combination is the ability to perform a full-text search on data at a very high speed. This is achieved through indexing, a process similar to the indexing of a book. Instead of searching the entire database to match the desired result, Elasticsearch uses indexing to start skimming over your result as soon as you begin your search.

Setting Up Elasticsearch with Laravel

Before you start working with Elasticsearch and Laravel, there are some prerequisites. You need to have an active Laravel application and Elasticsearch installed on your server or local machine.

Step 1: Install Elasticsearch

Elasticsearch can be installed on your server or local machine by following the official installation guide. After installation, you can check if your Elasticsearch instance is running by the following command in your command line:

curl -XGET 127.0.0.1:9200

Step 2: Install Elasticsearch Client for PHP Laravel

The next step is to install the Elasticsearch client for PHP Laravel. This can be done using the composer, a tool used for dependency management in PHP. Run the following command in your terminal:

composer require elasticsearch/elasticsearch

Step 3: Configure Laravel to Use Elasticsearch

After installing the Elasticsearch PHP client, the next step is to configure Laravel to use Elasticsearch. This can be done by adding Elasticsearch configuration in your Laravel config directory. Create a new file, elasticsearch.phpin the config directory and add the following configuration:

return [
'hosts' => [
env('ELASTIC_SEARCH_HOST', 'localhost:9200'),
],
];

This configuration tells Laravel to use Elasticsearch running on localhost at port 9200.

Indexing Data in Elasticsearch

Elasticsearch organizes its data in an inverted index. This structure allows for very fast full-text searches. Each index is made up of one or more shards, and each shard is a self-contained index. For our Laravel application, let’s create an index for our data.

Creating an Index

An index in Elasticsearch is like a table in a relational database. It has a mapping (like a schema in SQL) and can contain one or more documents. To create an index in Elasticsearch, you can send a PUT request to Elasticsearch with the name of the index. Here is a PHP code snippet that creates an index:

$client = \Elasticsearch\ClientBuilder::create()->build();
$params = ['index' => 'my_index'];
$response = $client->indices()->create($params);

In the code snippet above, we first create an Elasticsearch client using the ClientBuilder. Then, we define the parameters for the index (in this case, the index name is 'my_index'). Finally, we call the create method on the indices object to create the index.

Adding Data to the Index

Once the index is created, you can add data to it. The data in Elasticsearch is organized in documents, which are JSON objects that have keys and values. Each document is stored in an index and has a type and an id.

Here is a PHP code snippet that adds a document to an index:

$params = [
'index' => 'my_index',
'id' => 'my_id',
'body' => ['field1' => 'content1']
];

$response = $client->index($params);

In the code snippet above, we define the parameters for the document. The index is the name of the index where the document will be stored. This id is the ID of the document. The body is the content of the document, which is a JSON object.

Once the parameters are defined, we call the index method on the client to add the document to the index.

Searching Data in Elasticsearch

Elasticsearch provides a very powerful search functionality. It supports multi-language and geolocation data, and you can perform complex queries and aggregations.

Basic Search

The basic form of search in Elasticsearch is to use the _search endpoint. Here is a PHP code snippet that performs a basic search:

$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'field1' => 'content1'
]
]
]
];

$response = $client->search($params);

In the code snippet above, we first define the parameters for the search. This index is the name of the index where we want to search. The body contains the search query. In this case, we use a match query, which is a basic query that matches the exact content.

Once the parameters are defined, we call the search method on the client to perform the search.

The response of the search method is an array that contains the result of the search.

Advanced Search

Elasticsearch also supports more advanced forms of search. You can use boolean logic, wildcards, filtering, and sorting in your searches.

Here is a PHP code snippet that performs an advanced search:

$params = [
'index' => 'my_index',
'body' => [
'query' => [
'bool' => [
'must' => [
'match' => ['field1' => 'content1']
],
'filter' => [
'range' => [
'field2' => ['gte' => 5]
]
]
]
],
'sort' => [
'field2' => ['order' => 'desc']
]
]
];

$response = $client->search($params);

In the code snippet above, we use a bool query, which allows us to use boolean logic in our search. The must clause is equivalent to a logical AND, and the filter clause is used to filter the results of the query. The range query is used to filter the results that field2 are greater than or equal to 5. The sort clause is used to sort the results based on field2 in descending order.

Conclusion

Elasticsearch and Laravel are powerful tools that, when combined, can provide a robust and efficient search engine for your web applications. This guide has shown you how to set up Elasticsearch and Laravel and how to use them to index and search data. However, this is just the tip of the iceberg. Elasticsearch offers a myriad of features and capabilities that you can explore to further enhance your applications.

Feel free to Subscribe for more content like this 🔔, clap 👏🏻 , comment 💬, and share the article with anyone you’d like

And as it always has been, I appreciate your support, and thanks for reading.

--

--

Mohammad Roshandelpoor

Software Engineer | Laravel | PHP | Nuxt | Vue | with over 10 years of experience, have a deep understanding of software architecture