DEV Community

Tonko Mulder
Tonko Mulder

Posted on • Originally published at Medium on

First steps with Elasticsearch & Laravel

After working with Solr in past employment, I’ve alway been interested in indexing large amounts of data and processing that.

So recently I was told to look into Elasticsearch and I’ve been following the How to integrate your Laravel app with Elasticsearch post by Tony Messias from Made with love.

As it turns out that it’s actually quite simple, the Eloquent model that needs to be indexed has a trait which contains a created and deleted event. These are actually Model observer events, which determine if a piece of data should be indexed by Elasticsearch.

public function saved ($model)
{
    $this->elasticsearch->index([
        'index' => $model->getSearchIndex(),
        'type' => $model->getSearchType(),
        'id' => $model->id,
        'body' => $model->toSearchArray(),
    ]);
}

public function deleted ($model)
{
    $this->elasticsearch->delete([
        'index' => $model->getSearchIndex(),
        'type' => $model->getSearchType(),
        'id' => $model->id,
    ]);
}
Enter fullscreen mode Exit fullscreen mode

The first part was about getting data into Elasticsearch, the second part is about getting that data from Elasticsearch and presenting it on the Laravel side. Tony’s article is using a repository to interact with Elasticsearch. In that repository the following method is present to do the searching part.

private function searchOnElasticsearch (string $query): array
{
    $instance = new Article;

    $items = $this->search->search([
        'index' => $instance->getSearchIndex(),
        'type' => $instance->getSearchType(),
        'body' => [
           'query' => [
              'multi\_match' => [
              'fields' => ['title', 'body', 'tags'],
                    'query' => $query,
                ],
            ],
        ],
    ]);

return $items;
}
Enter fullscreen mode Exit fullscreen mode

It returns an array with the data it retrieved from Elasticsearch, which in turn can be used by Laravel as a data source.

So these were my first steps with Elasticsearch, I like how easy it actually was setting this up. Next is implementing this in a personal project, and trying to learn more about Elasticsearch in the meantime.

Top comments (2)

Collapse
 
azazqadir profile image
Muhammad Azaz Qadir

You can integrate Elasticsearch in Laravel easily by using Scout. Laravel Scout has pre-configured full text search settings. Install Laravel Scount and Elasticsearch and then integrate it in Laravel model.

Collapse
 
treggats profile image
Tonko Mulder

I am aware of that, but there are scenario's where you want full control over the Elasticsearch integration. In those cases you won't use Laravel Scout but Elasticsearch directly, like I've outlined in this post.